本文介紹了如何在 PHP 中鏈接方法?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
jQuery 讓我鏈接方法.我也記得在 PHP 中看到過同樣的東西,所以我寫了這個:
jQuery lets me chain methods. I also remember seeing the same in PHP so I wrote this:
class cat {
function meow() {
echo "meow!";
}
function purr() {
echo "purr!";
}
}
$kitty = new cat;
$kitty->meow()->purr();
我無法讓鏈條工作.它在喵喵叫之后立即產生一個致命錯誤.
I cannot get the chain to work. It generates a fatal error right after the meow.
推薦答案
為了回答您的 cat 示例,您的 cat 方法需要返回 $this
,即當前對象實例.然后你可以鏈接你的方法:
To answer your cat example, your cat's methods need to return $this
, which is the current object instance. Then you can chain your methods:
class cat {
function meow() {
echo "meow!";
return $this;
}
function purr() {
echo "purr!";
return $this;
}
}
現在你可以:
$kitty = new cat;
$kitty->meow()->purr();
有關該主題的真正有用的文章,請參見此處:http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html
For a really helpful article on the topic, see here: http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html
這篇關于如何在 PHP 中鏈接方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!