有关php对象的问题。

在使用KIRBY(一种CMS)的API时,发现了以下这种写法:

$page->children()->visible();

请问这种写法是什么意思,是对象中的函数中又嵌套函数吗?

阅读 2.2k
2 个回答

没看过它的源码,但是是这样的,$page->children() 是返回了一个对象,这个对象中有 visible() 这个方法的。所以可以这样调用,这也叫链式调用。

举个例子

class Wallet
{
    protected $money;
    
    public function money()
    {
        $this->money = new Money();
        return $this->money;
    }
}

class Money
{
    protected $total;
    
    public function used($count)
    {
        $this->total -= $count;
    }
}

这里就可以这样链式调用

$user = new User();
$user->money()->used(23);

链式调用而已,建议楼主多看看框架源码,框架很多都会以对象的方式返回

class Test{
    
    protected $_height;
    
    protected $_weight;
    
    public function setHeight($height)
    {
    
        $this->_height = $height;
        
        return $this;
    }
    
    public function setWeight($weight)
    {
    
        $this->_weight = $weight;
        
        return $this;
    }
    
    public function getBMI()
    {
        return $this->_weight/pow($this->_height,2);
    }

}

$obj = new Test();

$height = "1.85";
$weight = "80";
$bmi = $obj->setWeight($weight)->setHeight($height)->getBMI();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题