note 44465 added to function.call-user-func-array
| From: | patripaq at hotmail dot com | Date: | Fri, 06 Aug 2004 22:49:22 +0000 |
| Subject: | note 44465 added to function.call-user-func-array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-74107@lists.php.net to get a copy of this message | ||
I just started using PHP 5.0 and, so far, I'm loving it ! However, I had a problem the other
day and thought it would be a good idea to inform other programmers about the solution I found to
get around it. It concerns the new __constructor() function and the call_user_func_array()
function. What I wanted to do is create an object that can manage any number and any kind of
parameters. Here's the problematic code:
//--------------------------
class A {
function __construct() {
$args = func_get_args(); // Get arguments
// Class initialization...
}
function A() {
$args = func_get_args(); // Get arguments
call_user_func_array( array(&$this, '__construct'), $args ); // Infinite loop to
B::__construct()...
}
}
class B {
function __construct() {
$args = func_get_args(); // Get arguments
call_user_func_array( array(&$this, 'A'), $args ); // Initialize parent with
arguments
// Class initialization...
}
}
$obj = new B( 'param1', 'param2' );
//--------------------------
I suppose you can guess where the problem is located... In the A::A() function, the call to
__construct() using call_user_func_array() is redirected to B::__construct() instead of
A::__construct(). The only way I found to specify which constructor function I wanted to call was
to stop using A::__construct() and use the old fashion constructor instead. If anyone can find a
better way, feel free to add comments. Here's my solution. Hope it helps anyone.
//--------------------------
class A {
function A() {
$args = func_get_args(); // Get arguments
// Class initialization...
}
}
class B {
function __construct() {
$args = func_get_args(); // Get arguments
call_user_func_array( array(&$this, 'A'), $args ); // Initialize parent with
arguments
// Class initialization...
}
}
$obj = new B( 'param1', 'param2' );
//--------------------------
----
Manual Page -- http://www.php.net/manual/en/function.call-user-func-array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+44465
Delete -- http://master.php.net/manage/user-notes.php?action=delete+44465&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+44465&report=yes
Search -- http://master.php.net/manage/user-notes.php