Jump to content

[SOLVED] variable as classname


TiloW

Recommended Posts

Hey guys =)

 

Here's my problem:

// exemplary class
class Test
{
  static public DoSomething()
  {}
}

// reference of class "Test"
$testClassName = "Test";

// create new instance of class "Test"
$testInstance = new $testClassName();  // works just fine

// call static method of class "Test"
$testClassName::DoSomething(); // doesn't work

 

So.. How can i call a static method of a class which is strored in a variable?

 

Thanks for any help =)

Link to comment
https://forums.phpfreaks.com/topic/165696-solved-variable-as-classname/
Share on other sites

That's not an example of of a string being interpreted as a class name. That's an example of storing a string of value "Test" to a variable $testClassName.  If you want to reference a static method like that, you can do

 

Test::doSomething();

 

or else like

 

$testClassName = "Test";

eval($testClassName."::doSomething();");

Well.. I don't really get the difference because in

$testInstance = new $testClassName();

the value of $testClassName is interpreted as a name of a class ..isn't it?

 

No.  Class names (and functions) are not parsed inside quotes like that.  Only variables arrays and objects.

Why does what work...this?

Well.. I don't really get the difference because in

$testInstance = new $testClassName();

the value of $testClassName is interpreted as a name of a class ..isn't it?

 

edit:

 

Accidentally hit post.  It does work, because it will create an instance of the object using the value of that variable.  But that is not the same as linking that variable to the class, or somehow making an object out of a variable.  You are simply making use of the value.

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.