A Path Less Taken

Breaking with convention in a very conventional fashion. Powered by WordPress

"What would you attempt to do if you knew you could not fail?"
Dr. Robert Schuller

Sunday, April 19, 2009

Category: PHP Development Author: JJ 0 Comments

This is a simple technique, but I wanted to capture it here in the event that I ever had a use for it. Let’s assume that you have the name of a function as a variable in PHP and you want to call that function using the variable. Here is what you do.

1
2
3
4
5
6
7
function myFunc () 
{
   print "Welcome!" ;
}
 
$temp = "myFunc" ;
$temp () ;

That’s pretty easy stuff. You can extend this approach to PHP objects. Let’s say you have an instance of an object called $myObj and it has a public function named myFunc that takes one string parameter. Inside another object you could do something like this.

1
2
3
$temp = "myObj" ;
global $$temp ;
$temp->myFunc ("Welcome!") ;

That’s all there is to it. Without doing much research, it seems like this could be useful for a messaging system where the object registers to receive a message by providing its name and the message pump signals the object through a known method defined in an interface or a base class. This may not be the best approach, but it should work for a simple implementation.

No comments found. Please enter a comment if you have a question or contribution.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">