hq8501 发表于 2017-4-7 12:42:32

PHP中不错的类的调用方法

  $foo
->
bar
()->
bar
()->
bar
()->
bar
()->
hello
(); 是php框架中常用的形式。




  首先理解一
下$this,伪变量 $this
可以在当一个方法在对象内部调用时使用。$this
是一个到调用对象的引用,先看一下例子吧





<?php
class foo{
function bar() {
return $this;
}
function hello() {
echo "Hello";
}
}
$foo = new foo();
$foo->bar()->bar()->bar()->bar()->hello();
?>
  大家看到这种新颖的调用方法了吧,这样调的时候有一个好处就是很直观,如hello()方法是我们要
操作方法,而bar()是一些步骤方法,在这里我再写个类吧,可能更明显一些


<?php
class example {
var $name;
var $sex;
function name($name) {
$this->name = $name;
return $this;
}
function sex($sex) {
$this->sex = $sex;
return $this;
}
function trace() {
print("Name: {$this->name},Sex: {$this->sex}");
}
}
$person = new example;
$person->name("lisha")->sex("female")->trace();
/*output
Name:lisha,Sex:female
*/
?>
 
页: [1]
查看完整版本: PHP中不错的类的调用方法