PHP 4.3.11, call_user_func and instances of classes
| From: | David Otton | Date: | Wed, 26 Apr 2006 23:46:42 +0000 |
| Subject: | PHP 4.3.11, call_user_func and instances of classes | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-234896@lists.php.net to get a copy of this message | ||
A bit of an oddity, this. There's some example code attached which
illustrates my problem.
I am attempting to call a method of an instance of an class from
outside that instance, using call_user_func().
What's happening is that my attempt to call
array ($this, 'AddOne')
is silently being rewritten into a call to
array ('Test', 'Addone')
in other words, instead of calling $test->AddOne I'm calling
Test::Addone. Thus, my expected output:
Add:1,Add:2,Add:3,Subtract:2,Subtract:1,Subtract:0,
becomes
Add:1,Add:1,Add:1,Subtract:-1,Subtract:-1,Subtract:-1,
So, my question is twofold:
a) How can I accomplish this?
b) Why is PHP silently modifying my code to mean something I didn't
write, rather than throwing up an error?
<?php
$addition = $subtraction = null;
class Test {
var $x;
function Test ()
{
global $addition, $subtraction;
$this->x = 0;
$addition = array ($this, 'AddOne');
$subtraction = array ($this, 'SubtractOne');
doMath('+'); doMath('+'); doMath('+');
doMath('-'); doMath('-'); doMath('-');
}
function AddOne ()
{
$this->x++;
echo ("Add:".$this->x.",");
}
function SubtractOne ()
{
$this->x--;
echo ("Subtract:".$this->x.",");
}
}
function doMath($choice)
{
global $addition, $subtraction;
switch ($choice)
{
case '+':
call_user_func ($addition);
break;
case '-':
call_user_func ($subtraction);
break;
}
}
$test = new Test();
?>