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

I see a lot of code in which the calls look like this.

Example:

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

How to achieve what I wrote above?

+4
source share
3 answers

This means that $person, $person->headand $person->eyeshave properties that are other objects. headis a property $person, eyesis a property $person->head, etc.

So, when you set $person->head->size, for example, you set a property sizefor $person->head, that is, it $person->headmust be an object. In other words, a statement $person->head->size = 10;means set the size property of the head property of $person to 10.

Code example:

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

Output:

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"
}
+7
source

: .

:

. :

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

PHP chaning method is a secret, return each getter $ this method

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

-3
source

Source: https://habr.com/ru/post/1614257/


All Articles