这个类和子方法如何使用?

时间:2010-09-22 07:14:49

标签: php oop class

我一直在浏览一些php源代码,需要知道以下类和子方法如何使用:

<?php
$me = new Person;
$me->name("Franky")->surname("Chanyau")->phone("+22", "456 789");
?>

我对OOP非常了解,所以我不想要101.我只需要知道如何使上述代码成为可能。

6 个答案:

答案 0 :(得分:12)

可以通过

方法链接
return $this;

在方法结束时。

在这里解释: phpandstuff: Method Chaining Plus Magic Setters

这些方法通常设置一个实例变量,然后只返回$ this。

public function phone($param) {
  $this->phone = $param;
  return $this;
} 

答案 1 :(得分:3)

方法name() surname()phone()返回Person的实例。

你可以做到这一点
return $this;

这些方法很可能如下所示:

public function name($name) {
    $this->name = $name;
    return $this;
}

答案 2 :(得分:3)

像其他一些人所说的那样,它的流畅接口http://en.wikipedia.org/wiki/Fluent_interface#PHP基本理念是类的一个方法总是返回对象本身

class Car {
    private $speed;
    private $color;
    private $doors;

    public function setSpeed($speed){
        $this->speed = $speed;
        return $this;
    }

    public function setColor($color) {
        $this->color = $color;
        return $this;
    }

    public function setDoors($doors) {
        $this->doors = $doors;
        return $this;
    }
}

// Fluent interface
$myCar = new Car();
$myCar->setSpeed(100)->setColor('blue')->setDoors(5);

(通过维基)

答案 3 :(得分:1)

它被称为方法链。基本上每个类函数都返回对象本身($this),以便用户可以在返回的对象上调用更多函数。

public function name() {
    //other stuff...
    return $this;
}

http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html

http://www.electrictoolbox.com/php-method-chaining

答案 4 :(得分:0)

我们的想法是,如果我们返回$ this,那么我们可以将对象方法调用链接在一起。这是解决方案:

 <?php 

    class Person
    {
        private $strName;
        private $strSurname;
        private $ArrPhone = array();

        public function name($strName)
        {
            $this->strName = $strName;
            return $this; // returns $this i.e Person 
        }

        public function surname($strSurname)
        {
            $this->strSurname = $strSurname;
            return $this; // returns $this i.e Person
        }

        public function phone() 
        {   $this->ArrPhone = func_get_args(); //get arguments as array
            return $this; // returns $this i.e Person
        }

        public function __toString()
        {
            return $this->strName." ".$this->strSurname.", ".implode(" ",$this->ArrPhone);
        }
    }

    $me = new Person;
    echo $me->name("Franky")->surname("Chanyau")->phone("+22", "456 789");

?>

答案 5 :(得分:0)

更正答案,但要使代码有效,你应该写:

$me = new Person();

而不是

$me = new Person;