jQuery 允许我链式调用方法。我也记得在 PHP 中看到过同样的功能,所以我写了这个:
class cat {
function meow() {
echo "meow!";
}
function purr() {
echo "purr!";
}
}
$kitty = new cat;
$kitty->meow()->purr();
我无法让链条正常工作,它在喵声后立即生成致命错误。
jQuery 允许我链式调用方法。我也记得在 PHP 中看到过同样的功能,所以我写了这个:
class cat {
function meow() {
echo "meow!";
}
function purr() {
echo "purr!";
}
}
$kitty = new cat;
$kitty->meow()->purr();
我无法让链条正常工作,它在喵声后立即生成致命错误。
$this
,即当前对象实例。这样你就可以链接你的方法:class cat {
function meow() {
echo "meow!";
return $this;
}
function purr() {
echo "purr!";
return $this;
}
}
现在你可以这样做:
$kitty = new cat;
$kitty->meow()->purr();
这里有一篇非常有用的文章,介绍了这个主题:http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html
return $this;
只需从您的方法中返回$this
,即对象本身(的引用):
class Foo()
{
function f()
{
// ...
return $this;
}
}
$x = new Foo;
$x->f()->f()->f();
使用 PHP 5,您可以从方法中返回对象。因此,通过返回指向当前对象的 $this
,您可以实现方法链。