[英]How to get an Object's Object in PHP
我在使用PHP進行一些面向對象的編程時遇到了麻煩。
我基本上在一個類中有一個函數,它顯示一些文本:
public function text() {
echo 'text';
}
現在,我想將函數名稱存儲在arra,y中,以便稍后使用:
$functions = array('text_func' => 'text');
在另一個函數中,我想使用Array引用調用上述函數,因此我做了以下工作:
public function display() {
$this->functions['text_func']();
}
結果基本上是:
text();
我的問題是,如何使此功能運行? (正確的方式應該是: $this->text()
)。 但是我不能做這樣的事情,因為它給我一個錯誤:
$this->$this->functions['text_func']();
對我的問題有任何想法或解決方案嗎?
您仔細忽略的錯誤消息可能會警告您$this
不能轉換為字符串。 這為您提供了很好的線索。
(長答案是方法名稱是字符串。由於PHP是松散類型的,因此當它需要字符串時,它將嘗試將您提供的任何內容轉換為字符串。您的類缺少__toString()
方法,因此會出現錯誤。)
您可能想要這樣:
$this->{$this->functions['text_func']}();
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
這是一個來自PHP.net的示例,應該可以幫助您:
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>
資料來源: http : //www.php.net/manual/en/functions.variable-functions.php
$ this本身不包含引用,因此您應該嘗試
$this->display();
代替
$this->$this->functions['text_func'](); // WRONG
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.