I'm trying to get a reference
to a function
of an object
.
I tried what you can see on the way 2
with no success.
Any advice on this?
<?
function echoc($data) {
echo "
<pre>
";
print_r($data);
echo "</pre>
";
}
class Person {
const STATUS_SLEEPING = 0;
const STATUS_EATING = 1;
const STATUS_SEEING = 2;
const STATUS_WALKING = 3;
function __construct() {
$this->status = self::STATUS_SLEEPING;
}
function see() {
$this->status = self::STATUS_SEEING;
echo 'I\'m seeing now!';
}
function eat($what) {
$this->status = self::STATUS_EATING;
echo 'I\'m eating '.$what.' now!';
}
function walk() {
$this->status = self::STATUS_WALKING;
echo 'I\'m walking now!';
}
function getStatus() {
return $this->status;
}
function getStatusStr() {
switch ($this->status) {
case self::STATUS_SLEEPING: return 'STATUS_SLEEPING';
case self::STATUS_EATING: return 'STATUS_EATING';
case self::STATUS_SEEING: return 'STATUS_SEEING';
case self::STATUS_WALKING: return 'STATUS_WALKING';
}
}
};
$p = new Person();
echoc('Status: '.$p->getStatusStr());
$p->see();
echoc('Status: '.$p->getStatusStr());
$p->walk();
echoc('Status: '.$p->getStatusStr());
$way = 2;
switch ($way) {
case 1:
$p->eat('piza');
break;
case 2:
$method = 'eat'; // the name of the function is stored on a variable
// begin of code I'm looking for
$callback = $p->$method; // I tried this with no success
// end of code I'm looking for
call_user_func($callback, 'pizza'); // this line cannot be changed. I'm not allowed to
break;
}
echoc('Status: '.$p->getStatusStr());
?>