Calling Variable Class / Method Programmatically
I have a method in a variable named class that I need to call dynamically, how can I call this:
$foo = "object"
Where object is a specific class
How do 开发者_如何学PythonI call this in PHP?
$foo::method()
The wording of the question is confusing but from what I understand, if you want to set $foo
to a specific class, lets call it Foo
you can do this:
$foo = new Foo;
Here is our class Foo
class Foo {
public $aMemberVar = 'aMemberVar Member Variable';
public $aFuncName = 'aMemberFunc';
function aMemberFunc() {
print 'Inside `aMemberFunc()`';
}
}
If you want to access a class variable Foo
and set it to a variable you can do this:
$myVar = 'aMemberVar';
print $foo->$myVar //prints "aMemberVar Member Variable"
Also to clarify $foo::method()
implies that $foo
is a static class, and static classes cannot be instantiated but they can call on its class method method()
by using the scope resolution operator (::
)
Hope this helps.
$$foo::method();
See PHP variable variables
精彩评论