[英]Chaining a new object instance in PHP
我們有以下鏈接:
$obj = new obj();
$obj->setname($params1)->setcolor($params2);
有沒有辦法在一行上進行相同的鏈接,而不創建虛擬函數?
PS:我想跳過構造函數本身在新行上的部分。 我想構造對象並在同一行開始鏈接。 像這樣的東西:
$obj = new obj()->setname($params1)->setcolor($params2);
從PHP 5.4開始,已添加實例化的類成員訪問權限,因此您可以這樣做:
$obj = (new obj())->setname($params1)->setcolor($params2);
在以前的版本中,像你一樣我討厭你必須在一行上實例化對象然后開始在另一行上使用它,所以我有一個全局函數_i()
,如下所示:
function _i($i) { return $i; }
我這樣使用它:
_i(new Obj)->doThis($param)->doThat($param2);
有些人會發現它很丑,但PHP缺乏語言表達能力,所以它對我有用:)
我為它使用類的靜態函數。
class a{
static public function gets($args){
return new self($args);
}
public function do_other(){
}
}
a::gets()->do_other();
通常我有更多的靜態方法來不同的用法
您也可以使用Singleton模式中的此技術(不使用單例模式):
<?php
class test
{
public function __construct() {
}
public static function getInstance() {
return new test();
}
public function chain() {
echo 'ok';
}
}
// outputs 'ok'
$test = test::getInstance()->chain();
如果你總是在函數中返回對象本身,那么應該是可能的。
function setname($param) {
// set the name etc..
return $this;
}
您還可以使用PHP類型提示來確保僅將正確的對象用作參數
function instance(sdtClass $instance) { return $instance }
或者作為使用類名的靜態方法
class CustomClass{
static public function gets(CustomClass $obj){
return $obj;
}
}
當然可以。 Simplt return this
每個函數結束時,返回對象讓你的下一個鏈接的功能,可以使用它。
<?php
class A
{
public __constructor()
{ .... }
public function B($params)
{
//Processing
return this;
}
public function C($params)
{
//Processing
return this;
}
public function D($params)
{
//Processing
}
}
$O = new A();
$O->B($params)->C($params)->D($params); //Will work because B and C return this
$O->B($params)->D($params)->C($params); //WILL NOT work because D doesn't return this
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.