PHP字符串到对象名称
发布时间:2020-12-13 17:03:14 所属栏目:PHP教程 来源:网络整理
导读:好的我有一个字符串…… $a_string = "Product"; 我想在调用这样的对象时使用这个字符串: $this-$a_string-some_function(); 狄更斯如何动态调用该对象? (不要以为我在PHP 5心中) 解决方法 所以你要使用的代码是: $a_string = "Product";$this-$a_string-
好的我有一个字符串……
$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(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |