如何实现这一点:object-> object->属性

时间:2015-11-03 11:57:42

标签: php oop

我看到很多代码都是这样的调用。

一个例子:

$person->head->eyes->color = "brown";
$person->head->size = 10;
$person->name = "Daniel";

我如何实现上面所写的内容?

3 个答案:

答案 0 :(得分:7)

这仅表示$person$person->head$person->eyes各自具有属于其他对象的属性。 head$person的属性,eyes属性为$person->head,依此类推。

因此,例如,当您设置$person->head->size时,您设置的size属性为$person->head,这意味着$person->head必须是对象。换句话说,语句$person->head->size = 10;表示set the size property of the head property of $person to 10

示例代码:

<?php

class Eyes
{
    var $color = null;
}

class Head
{
    var $eyes = null;
    var $size = null;


    function __construct()
    {
        $this->eyes = new Eyes();
    }
}

class Person
{
    var $head = null;
    var $name = null;

    function __construct()
    {
        $this->head = new Head();
    }
}

$person = new Person();
$person->head->eyes->color = "brown";
$person->head->size = 10;
$person->name = "Daniel";

var_dump($person);

输出:

class Person#1 (2) {
  public $head =>
  class Head#2 (2) {
    public $eyes =>
    class Eyes#3 (1) {
      public $color =>
      string(5) "brown"
    }
    public $size =>
    int(10)
  }
  public $name =>
  string(6) "Daniel"
}

答案 1 :(得分:0)

第一件事:你的例子中没有调用任何方法。

答案:

这可以通过使用另一个对象实例作为属性来实现。例如:

class Head{
    public $size, $eyes, $etc;
}

class Person{
    public $name, $age, $head;

    public function __construct(){
        $this->head = new Head();
    }
}

$person = new Person();
$person->head->size = 'XL';

这是一种做法

您还可以将数组转换为对象。这将生成带有数组索引作为属性的stdClass实例:

$person = array(
    'name' => 'Foo',
    'age' => 20
);

$personObject = (object) $person;
var_dump($personObject);

答案 2 :(得分:-3)

PHP方法chaning是秘密,每个getter方法返回$ this

class Person
{
    public function head()
    {
        ...
        return $this;
    }

    public function eyes()
    {
        ...
        return $this;
    }
}

$person->head->eyes->color = "brown";

https://en.wikipedia.org/wiki/Method_chaining#PHP