note 115527 added to function.call-user-func-array
| From: | stanislav dot eckert at vizson dot de | Date: | Sun, 10 Aug 2014 00:48:38 +0000 |
| Subject: | note 115527 added to function.call-user-func-array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-200147@lists.php.net to get a copy of this message | ||
Please note, that when calling call_user_func_array() to redirect parameters between inherited
classes, you should not use $this, because $this always refers to the class which has been
instantiated. The following code even seems to crash PHP (PHP does not report error but the process
simply terminates), because the the parameters are redirected only one level up (to class foo_bar2):
<?php
class foo_bar1
{
public function __construct()
{
echo __CLASS__ . PHP_EOL;
if (func_num_args() > 0)
{
$constructorArgs = func_get_args();
call_user_func_array(array($this, 'parent::__construct'), $constructorArgs);
}
else
{
parent::__construct();
}
}
}
class foo_bar2 extends foo_bar1
{
public function __construct()
{
echo __CLASS__ . PHP_EOL;
if (func_num_args() > 0)
{
$constructorArgs = func_get_args();
call_user_func_array(array($this, 'parent::__construct'), $constructorArgs);
}
else
{
parent::__construct();
}
}
}
class foo_bar3 extends foo_bar2
{
public function __construct()
{
echo __CLASS__ . PHP_EOL;
if (func_num_args() > 0)
{
$constructorArgs = func_get_args();
call_user_func_array(array($this, 'parent::__construct'), $constructorArgs);
}
else
{
parent::__construct();
}
}
}
$f = new foo_bar3("abc");
?>
Instead, use the direct name of the class as string or, better, the magic constant __CLASS__ in
call_user_func_array(), like:
call_user_func_array(array(__CLASS__, 'parent::__construct'), $constructorArgs);
Then the parameters will be correctly redirected to the lowest base class.
----
Server IP: 72.52.91.14
Probable Submitter: 85.179.7.43
----
Manual Page -- http://php.net/manual/en/function.call-user-func-array.php
Edit -- https://master.php.net/note/edit/115527
Del: integrated -- https://master.php.net/note/delete/115527/integrated
Del: useless -- https://master.php.net/note/delete/115527/useless
Del: bad code -- https://master.php.net/note/delete/115527/bad+code
Del: spam -- https://master.php.net/note/delete/115527/spam
Del: non-english -- https://master.php.net/note/delete/115527/non-english
Del: in docs -- https://master.php.net/note/delete/115527/in+docs
Del: other reasons-- https://master.php.net/note/delete/115527
Reject -- https://master.php.net/note/reject/115527
Search -- https://master.php.net/manage/user-notes.php