This works but...

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

This works but...

Post 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();
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: This works but...

Post 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)
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
timWebUK
Forum Contributor
Posts: 239
Joined: Thu Oct 29, 2009 6:48 am
Location: UK

Re: This works but...

Post 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?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: This works but...

Post 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
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: This works but...

Post 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.
Post Reply