2016-12-04 55 views
0

所以我現在有一個類,並想使類通過能夠調用類的實例作爲功能,如__toString魔術方法,它輸出調用時字符串,而不是可以調用$instance()作爲一個函數調用更清潔,有它叫。如何從實例調用中調用類函數?

像:

class MyClass { 
    public function __onCall() { 
    echo 'This was called when the user called the instance!'; 
    }  
} 

$instance = new MyClass(); 
$instance(); 
//opts: This was called when the user called the instance! 

基本上我希望能夠給鏈級的功能,切斷一條鏈是會通過調用實例函數被調用了很多。

語法我想:

$Class('Some String')->SomeFunction()->AnotherFunction(); 

語法我有:

$Class->select_string('Some String')->SomeFunction()->AnotherFunction(); 

:-)

+0

我不明白爲什麼你真的需要有一個結構類似這樣的時候,其實你正在處理OOP。 – Aldee

+0

@Aldee這不是它正在使用的確切方式,它的意思做這樣一個電話:'$字符串(「的TestString」) - > AnotherCall() - > MoreCalls()',因爲這是更簡單的語法比'$字符串 - > select_string('TestString') - > AnotherCall-> MoreCalls()'如果這是有道理的,所以這就是我想使用這種方法的原因。 '':-)請 – Jek

+0

檢查以下:-) – Aldee

回答

1

確定。我明白你的意思了。所以你想要一個流暢的方法鏈。這實際上是answered by another thread

希望這有助於。

+0

我的答案啊哈啊,我知道如何鏈的方法,我只是想能叫那將直接有很多來自實例調用功能切一個鏈斷我會把這個添加到我的問題中。 :〜) – Jek

+0

啊。好的,我明白了。我想這可能是你感興趣的http://php.net/manual/en/language.oop5.anonymous.php - 但這只是PHP 7我猜。 – Aldee

+0

啊哈我發現了,沒想到看神奇的方法,'__invoke'! http://php.net/manual/en/language.oop5.magic.php#object.invoke – Jek

相關問題