如何实现这一点:对象->;对象->;所有物


How to achieve this: object->object->property

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

一个例子:

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

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

这只是意味着$person$person->head$person->eyes各自具有其他对象的属性。head$person的性质,eyes$person->head的性质,依此类推

因此,例如,当您设置$person->head->size时,您正在设置$person->headsize属性,这意味着$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"
}

第一件事:在您的示例中没有调用任何方法。

答案:

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

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);

PHP方法更改是秘密,每个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