<?php
class foo
{
private $callVar = false;
private $constructorVar = false;
public function __construct()
{
$this->constructorVar = get_class($this);
}
public function __call($methodName, $arguments)
{
$this->callVar = get_class($this);
call_user_func_array(array($this, $methodName), $arguments);
}
protected function method($params)
{
echo('<br>Call var: '.$this->callVar.'<br>Constructor var: '.$this->constructorVar);
}
}
class foo_sec extends foo
{
protected function method($params)
{
echo 'First call: ';
parent::method($params);
echo '<br> Second call: ';
$test = new foo_trd();
$test->method('param2');
}
}
class foo_trd extends foo
{
}
$m = new foo_sec();
$m->method('param');
?>
Gives this result:
First call:
Call var: foo_sec
Constructor var: foo_sec
Second call:
Call var:
Constructor var: foo_trd
This code should return the name of the instance that is currently running, but if the instance is inside another instance, the class name is empty in second one. Is this a PHP bug or some other issue I'm missing?
In other words, the Call var
in the second call should be foo_trd
- not empty.
I believe you are experiencing something interesting to do with PHP and its inheritance visibility.
In short when you are inside and instance of Foo
you have access to the protected
and private
scope of all other instances that also extend Foo
. As you are allowed to access the protected method()
directly you will skip the call to __call()
.
This can actually be useful when you want to make your constructor private and enforce factories.