Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.