[英]How to chain methods and return them inside a method? OOP-PHP
我需要重建頭腳本和鏈接,以便創建一個可用於將來引用的類。
我開始喜歡:
class HeadClas{
public static $headprint;
function __construct(){
$this->headprint = "";
}
function addLinks(){
$this->headprint .= "addLinks";
return $this;
}
function addMeta(){
$this->headprint .= "addMeta";
return $this;
}
function printHead(){
return $this->headprint;
}
}
在上述情況下,我需要做
$print = new HeadClas;
$print->addLinks()->addMeta();
我想做
$print = new HeadClas;
$print->printHead();
我確實嘗試過
function printHead(){
return $this->addMeta()->addLinks();
}
但是比我需要做的
$print->printHead()->headprint;
我在這里想念什么? 任何幫助表示贊賞!
首先,應將$headprint
字段$headprint
非靜態。 將其設置為靜態使其成為將來所有實例的相同參考,這將產生不良結果。
printHead()
應該像方法名稱所建議的那樣打印該字段的內容。
class HeadClass {
public $headprint;
function __construct() {
$this->headprint = "";
}
function addLinks() {
$this->headprint .= "addLinks";
return $this;
}
function addMeta() {
$this->headprint .= "addMeta";
return $this;
}
function printHead() {
$this->addLinks()->addMeta();
echo $this->headprint;
}
}
$printer = new HeadClass();
$printer->printHead();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.