Forum Moderators: coopster

Message Too Old, No Replies

forwarding function arguments

Using a function to call another function or class

         

topwebdesigns

3:30 pm on Jan 13, 2010 (gmt 0)

10+ Year Member



Hi there, i'm not sure 100% how to phrase the question and explain what i'm trying to do, so bare with me.

Basically, i'd like to try and interupt a function call or class call and do some checks first. The best way I can think to do so is to call a function that does its checks and returns the function or class e.g:


function getClass($className) {
//do stuff
return new $className;
}

$class = getClass("className");

That works in its simplest format, but of course classes and functions have arguments sent to them and this poses a problem, as the possibilities for the different arguments are endless.

I thought there'd be an easy way around this using func_get_args. However I don't know how to then send the arguments to the function or class other than in an array e.g:


function getClass() {
$args = func_get_args();

//The class name should be the first paramater and we don't want to send it to the class.
$className = array_shift($args);

//do stuff
return new $className($args);
}

$class = getClass("className","someOption","anotherOption");

Does anyone have any suggestions? Obviously my first port of call was Google, but I haven't been able to find anything, although i'm not sure exactly what keywords one would use in this instance.

p.s. code tags in my post seemed to mess up the code (really small text), so I put them in quote tags. Is there something I should know or is this a common bug?

topwebdesigns

3:49 pm on Jan 13, 2010 (gmt 0)

10+ Year Member



Just to clarify. The one solution i've come up with so far, that i'm not 100% happy with, is in each of the functions and classes in my script to just accept a single argument as an array and then use the list function, e.g:


class className {
public function __construct($args) {
list($this->option1, $this->option2, $this->option3) = $args;
}
}

function getClass() {
$args = func_get_args();

//The class name should be the first paramater and we don't want to send it to the class.
$className = array_shift($args);

//do stuff
return new $className($args);
}

$class = getClass("className","someOption","anotherOption");

Of course this means a little extra processing and slightly messier code as i'd have to check for required arguments rather than the function already expecting it.

What i'm actually wanting to do is check for existances of an object first. For instance, I've found I may sometimes call the object for a product twice when I try to get all the cart items and all the products on a certain page, for instance.

So in this instance, if it exists i'd return the existing object. That way I don't do sql queries multiple times and if I modify the product the old data won't still be present in the other instance of the object.