Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable class names - possible? 2

Status
Not open for further replies.

dyke

Technical User
Feb 14, 2005
3
PL
Is it possible to use the following syntax in PHP4 (or anything that would allow me to change the class refered to depending on a variable holding a class name):
if (...)
{ $var='classA'; }
else
{ $var='classB'; }

$var::method($param1,$param2);

Thank you in advance for your help. I have been looking for a solution to this problem for hours.
 
I don't think it is possible to do it the way you are specifying (as far as I know), using it as a static class.

You can, however, instantiate the object first and use that reference:

Code:
if (...)
{ $var='classA'; }
else
{ $var='classB'; }

$obj = new $var;
$obj->method($param1,$param2);
unset($obj);
 
Good answer, tweenerz.

I've never seen a good reason for calling methods statically, and whenever I've used something that relies on it, it always seems a little backwards and broken when it I try to extend it through inheritance.
 
Well, in truly object oriented languages, static methods can be very useful. For example, in Java, if you want to change an input value into an integer (which is necessary since Java is strongly typed - unlike PHP which will convert automatically), you would simply call the static method parseInt
Code:
int newInputValue = Integer.parseInt(inputValue);
as opposed to instantiatng a Integer object, calling the method, then destrying the String object.
Code:
Integer intObj  = new Integer();
int newInputValue = intObj.parseInt(inputValue);
In the above code, you now have an object taking up memory that you will probably never use again.
 
Thank you for your help.

I was hoping to avoid having to create an object. But I followed the tip of tweenerz and it works fine for me.
 
If you want to call a class method without knowing the name of the class in advance and without having to instantiate an object, I recommend that you take a look at call_user_func():

The following code snipped is from the call_user_func() online manual page:

Code:
<?php
class myclass {
   function say_hello() 
   {
       echo "Hello!\n";
   }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
?>

Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Unless I am 100% sure, this is why I always put "as far as I know" in my responses. That way I don't look like an ass later.

Thanks, sleipner, I learned something new.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top