How does this class and helper methods work?

I am looking at the php source code and should know how the following classes and sub-methods work:

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

I have pretty solid OOP knowledge, so I don't want 101. I just need to know how to make the above code possible.

+5
source share
6 answers

The method chain is possible

return $this;

at the end of the method.

Explained here: phpandstuff: Chaining Plus Magic Setters method

These methods usually set the instance variable and then simply return $ this.

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

methods name() surname()and phone()return an instance of Person. you can accomplish this with

return $this;

, :

public function name($name) {
    $this->name = $name;
    return $this;
}
+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);

( wiki)

+3

, $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");

?>
0

, , :

$me = new Person();

$me = new Person;
0
source

All Articles