php中的步骤链
程序员文章站
2022-06-06 08:19:53
...
php中的方法链
在如zend,cakephp等不少框架中,会看到如下面的类的调用方式,如
$obj->foo()->bar()->anotherMethod();
这个其实是利用了PHP中的方法链的调用方法,下面看个例子就明白了:
class Person
{
private $name;
private $age;
public function setName($Name)
{
$this->name = $Name;
}
public function setAge($Age)
{
$this->age = $Age;
}
public function findMe()
{
echo "My name is ".$this->name." and I am ".$this->age. " years old.";
}
}
正常方式的调用:
$myself = new Person();
$myself->setName('Arvind Bhardwaj');
$myself->setAge('22');
$myself->findMe();
用方法链的话:
class Person
{
private $name;
private $age;
public function setName($Name)
{
$this->name = $Name;
return $this;//Returns object of 'this' i.e Person class
}
public function setAge($Age)
{
$this->age = $Age;
return $this;//Again returns object of 'this' i.e Person class
}
public function findMe()
{
echo "My name is ".$this->name." and I am ".$this->age. " years old.";
}
}
调用时就可以:
$myself = new Person();
$myself->setName('Arvind Bhardwaj')->setAge('22')->findMe();
在如zend,cakephp等不少框架中,会看到如下面的类的调用方式,如
$obj->foo()->bar()->anotherMethod();
这个其实是利用了PHP中的方法链的调用方法,下面看个例子就明白了:
class Person
{
private $name;
private $age;
public function setName($Name)
{
$this->name = $Name;
}
public function setAge($Age)
{
$this->age = $Age;
}
public function findMe()
{
echo "My name is ".$this->name." and I am ".$this->age. " years old.";
}
}
正常方式的调用:
$myself = new Person();
$myself->setName('Arvind Bhardwaj');
$myself->setAge('22');
$myself->findMe();
用方法链的话:
class Person
{
private $name;
private $age;
public function setName($Name)
{
$this->name = $Name;
return $this;//Returns object of 'this' i.e Person class
}
public function setAge($Age)
{
$this->age = $Age;
return $this;//Again returns object of 'this' i.e Person class
}
public function findMe()
{
echo "My name is ".$this->name." and I am ".$this->age. " years old.";
}
}
调用时就可以:
$myself = new Person();
$myself->setName('Arvind Bhardwaj')->setAge('22')->findMe();
相关文章
相关视频
上一篇: PHP中ini_set和ini_get函数的用法小结
下一篇: PHP4用户手册:函数-file