Page 1 of 1

This works but...

Posted: Fri Sep 10, 2010 3:16 am
by Benjamin
I'm using some callbacks to do some tricky things in wordpress, trying to add complex features without modifying the core codebase. So I came up with this, which does what I need it to do, but I'm wondering if it may crash and burn at one point or another...

Code: Select all

<?php
class foo  {
    public function __call($name, $args) {
        echo "$name called";
    }
}

$f = new foo();
$n = (string) 1;

$f->$n();

Re: This works but...

Posted: Fri Sep 10, 2010 4:39 am
by VladSun
Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
So, there might be a chance it will crash someday (i.e. future PHP versions)

Re: This works but...

Posted: Fri Sep 10, 2010 10:58 am
by timWebUK
I was wondering why you initialise the variable like this:

Code: Select all

$n = (string) 1;
And, why you use underscores at the start of your function name? Is there documentation benefit that you find from doing this?

Re: This works but...

Posted: Fri Sep 10, 2010 11:17 am
by John Cartwright
timWebUK wrote:And, why you use underscores at the start of your function name? Is there documentation benefit that you find from doing this?
__call is a magic method

Re: This works but...

Posted: Fri Sep 10, 2010 1:16 pm
by Benjamin
timWebUK wrote:I was wondering why you initialise the variable like this:

Code: Select all

$n = (string) 1;
Because the method name must be a string, not an integer. I was leaning towards using this for efficiency reasons, but I ended up using strings (alpha-characters) in a way that is just as efficient, so it's good. I don't think that this would ever stop working in the future, but I'd rather be safe. That was my main concern.