Jump to content

using the __call() magic method


marcelobm

Recommended Posts

Hi there every one, i'm writing a class that create instances of other classes and I want to use the __call() magic method to make it more compact and dynamic. here is a basic example of what I'm trying to achieve.

 

The code bellow is the working code.

<?php

class creator{
    private $objects = array();
    public function createObj1($param1, $param2, $param3){
        $this->objects[]=new Obj1($param1, $param2, $param3);
    }  
    public function createObj2($param1, $param2){
        $this->objects[]=new Obj2($param1, $param2);
    }  
}
?>

 

Now I want the same functionality but using just the __call(), something like this

<?php
class creator{
    private $objects = array();
    public function __call($name, $args){
        $this->objects[]=new $name($param1, $param2);
    }  
}
?>

So, the main problem is, in the $args variable i get an array with all the args passed,

How can I make the call to create a new object when in the object constructor are individual parameters needed and not an array of parameters.

 

Thank you in advance.

 

Link to comment
https://forums.phpfreaks.com/topic/247202-using-the-__call-magic-method/
Share on other sites

I solved it this way:

 

<?php
<?php
class creator{
    private $objects = array();
    public function __call($name, $args){
	$func = '';
	for($i=0; $i < count($args); $i++){
		$func .= "\$arguments[{$i}], ";
	}

	$func = "new ".$name."(".substr($func, 0, -2).");";

	eval("\$this->objects[] =  $func");   
    }  
}
?>

 

This work perfect, but if any of you have a better Idea i'll be glad to hear it

Don't ever use eval() for something like this, a solution like call_user_func_array is the most correct solution.  Eval() is for testing, debugging, and for when you've reached a level of skill where you know for a fact that PHP cannot do what you need it to do with the native functionality.

 

-Dan

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.