Jump to content

getting methods to work dynamically


purencool

Recommended Posts

Hi PhpFreaks,

 

I have a method that I need to be initialised  dynamically and I am not sure if the code below will work I have been able to workout if the method exists

but I have not found a way to it get to return the array. Has anyone go any ideas?

 

The error I get is: Catchable fatal error: Object of class Forms could not be converted to string

public function setMethodForms($methodName){
	echo $methodName." and does it exist ". (int)method_exists($this->formsObj, $methodName);

	//test to see if the method exists 
	if ((int)method_exists($this->formsObj, $methodName) == 1){
		//if it does execute 
		//print_r ($this->formsObj->projects()); //test to see if object works
		$return call_user_func($this->formsObj."->".$methodName."()");
	}
	return $return; 
}


 

 

Link to comment
Share on other sites

I think you need eval to run it on the fly

 

public function setMethodForms($methodName){
	echo $methodName." and does it exist ". (int)method_exists($this->formsObj, $methodName);

	//test to see if the method exists 
	if ((int)method_exists($this->formsObj, $methodName) == 1){
		//if it does exist
		eval ('$arrProjects = $this->formsObj->' . $methodName . '()'); 
		$return $arrProjects;
	}
	return false; 
}

 

i haven't checked the code to test it for typos, but you have to evalulate the code, pass the response to a variable called $arrProjects which is then returned.

Link to comment
Share on other sites

Thanks for all your feedback.

 

I found a way that is very clean. This is the completed code it gets an array of objects finds the method that then executes it.

 

 

public function getMethodForms($methodName){

	foreach ($this->formsObj as $key => $Obj){
	//test to see if the method exists 
	if ((int)method_exists($Obj, $methodName) == 1){
		//if it does execute 
		$return= $Obj->{$methodName}();
	}

	}
	//print_r($return);
	return $return;
}

Link to comment
Share on other sites

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.