note 44465 deleted from function.call-user-func-array by cmb

From: Date: Sun, 30 Aug 2015 18:13:53 +0000
Subject: note 44465 deleted from function.call-user-func-array by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-203518@lists.php.net to get a copy of this message
Note Submitter: patripaq at hotmail dot com ---- 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: <?php //-------------------------- 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. <?php //-------------------------- 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' ); //-------------------------- ?>

« previous php.notes (#203518) next »