這個問題在這里已經有了答案: PHP 方法鏈還是流利的介面? (10 個回答) 4 小時前關閉。
我想訪問下面的 php 函式。我有一個 php 類,它有一些屬性和方法。但我想用箭頭函式訪問那些方法。像 funcA()->funcB(); 請檢查以下代碼以供參考 [注意:我不知道技術名稱。所以我不能在谷歌上搜索它:(]
class myClass{
# PROPERITES
private $var1;
private $var2;
# FUNCTION A
public function FuncA($number)
{
// Get the value & set into property
$this->var1 = $number;
}
# FUNCTION B
private function FuncB()
{
// Do process & Set value into property for other uses
$this->var2 = $this->var1 10;
}
# FUNCTION C
public function FuncC()
{
// Show result
return $this->var2;
}
}
現在我想像這樣訪問這個類和函式
$ob = new myClass();
$ob->FuncA(10)->FuncC();
uj5u.com熱心網友回復:
它被稱為“方法鏈接”并且能夠做到這一點,方法需要回傳它自己的實體:
class Foo
{
public function methodA()
{
// do stuff
// Return the current class instance
return $this;
}
public function methodB()
{
// do stuff
// Return the current class instance
return $this;
}
public function methodC()
{
// Return a value. You won't be able to keep chaining after calling this
return $this->something;
}
}
現在你可以這樣稱呼他們:
$foo = new Foo;
$val = $foo->methodA()->methodB()->methodC();
請注意,您只能對回傳的方法執行此操作$this,因此在此示例中,您需要methodC()最后呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429022.html
