php字符串对象,PHP字符串到对象名称
好的我有一個(gè)字符串……
$a_string = "Product";
我想在調(diào)用這樣的對(duì)象時(shí)使用這個(gè)字符串:
$this->$a_string->some_function();
狄更斯如何動(dòng)態(tài)調(diào)用該對(duì)象?
(不要以為我在PHP 5心中)
解決方法:
所以你要使用的代碼是:
$a_string = "Product";
$this->$a_string->some_function();
這段代碼暗示了一些事情.一個(gè)名為Product的類(lèi),其方法為some_function(). $this具有特殊含義,僅在類(lèi)定義中有效.所以另一個(gè)類(lèi)將擁有Product類(lèi)的成員.
因此,為了使您的代碼合法,這是代碼.
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();
}
}
然后你可以用這個(gè)來(lái)調(diào)用它:
$MyInstanceOfAnotherClass = new AnotherClass();
$MyInstanceOfAnotherClass->callSomeCode();
標(biāo)簽:php,oop,string
來(lái)源: https://codeday.me/bug/20190627/1300076.html
總結(jié)
以上是生活随笔為你收集整理的php字符串对象,PHP字符串到对象名称的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 峰米T1怎么登陆腾讯会员
- 下一篇: 影之刃3金乌秘境怎么开启