好的我有一个字符串……
$a_string = "Product";
我想在调用这样的对象时使用这个字符串:
$this->$a_string->some_function();
狄更斯如何动态调用该对象?
(不要以为我在PHP 5心中)
解决方法:
所以你要使用的代码是:
$a_string = "Product";
$this->$a_string->some_function();
这段代码暗示了一些事情.一个名为Product的类,其方法为some_function(). $this具有特殊含义,仅在类定义中有效.所以另一个类将拥有Product类的成员.
因此,为了使您的代码合法,这是代码.
class Product {
public function some_function() {
print "I just printed Product->some_function()!";
}
}
class AnotherClass {
public $Product;
function __construct() {
$this->Product = new Product();
}
public function callSomeCode() {
// Here's your code!
$a_string = "Product";
$this->$a_string->some_function();
}
}
然后你可以用这个来调用它:
$MyInstanceOfAnotherClass = new AnotherClass();
$MyInstanceOfAnotherClass->callSomeCode();
标签:php,oop,string
来源: https://codeday.me/bug/20190627/1300076.html