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
https://forums.phpfreaks.com/topic/256515-getting-methods-to-work-dynamically/
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.

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;
}

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.