note 77522 rejected from function.call-user-func by nlopess
| From: | nlopess@php.net | Date: | Sun, 02 Sep 2007 10:22:03 +0000 |
| Subject: | note 77522 rejected from function.call-user-func by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-130099@lists.php.net to get a copy of this message | ||
Note Submitter: deadimp at gmail dot com
----
I don't entirely understand why PHP's OOP is structured as it is. I'm attempting to
design a virtual class, which is meant to sort-of emulate C++'s multiple inheritance with
classes, since I can't find it in PHP.
I wanted to take advantage of PHP's loose class structure, which allows you to call any
non-static method in the scope of any class (as long as the method is accessible). However, it seems
that call_user_func() (and by relation call_user_func_array()) does not make its calls in the scope
of the class, which is something I don't get. I'm trying to use callback to call the
defined bases' constructors, and also in __call() to call the bases' functions using
$this->func(). So far, the only way is to use eval().
I'm running PHP 5.2.2, part of XAMPP (for Windows).
Code Example:
<?php
class Base {
var $name="Tim", $age;
function __construct($age=12) {
$this->age=$age;
echo "Base of age $age!<br>";
}
}
class Test {
function __construct() {
Base::__construct(); //It's not inherited, yet this works perfectly
//What you think would work
call_user_func(array("Child","__construct")); //But it doesn't -
it's not in scope
//Using the method levi stated on the call_user_func_array() page, but not using
'parent' (since it's not the parent)
call_user_func(array($this,"Child::__construct")); //This doesn't work either - I
tried it with parent, and it worked (when one was defined)
//I don't think I can test what serge belychev suggested, since I'm running 5.2.2 at
the moment
call_user_func("Child::__construct"); //? Will it do the same thing as the others?
//After revising this post a little, I realized I had forgotten about eval()
eval("Child::__construct();"); //This actually works! However, it's slower and a
pain to pass arguments
//Crappy solution for arguments: Before eval, store arguments in array, and then add
$arg[0],$arg[1],... etc to function call
echo $this->age;
}
}
$obj=new Test();
?>
There are two ways that I'm thinking of to resolve this:
> Use a different method of callback, allowing the class to be defined in the function name,
> rather than the first argument of the array
> Have call_user_func[...]() called in the scope classes, if applicable.
I don't see any exra downfalls that could happen with this.
I'll post an example of that virtual class once I upload the next version of Thacmus
(http://sourceforge.net/projects/thacmus/).