PHP objects , how to read

I am trying to figure out, how do we read this $result->orderResult->shipmentResponses->faults I have seen
$result->orderResult but not such a double -> what does it mean and how to read it?

The following two are equivalent (do the exact same thing)

$faults = $result->orderResult->shipmentResponses->faults;

and

$orderResult = $result->orderResult;
$shipmentResponses = $orderResult->shipmentResponses;
$faults = $shipmentResponses->faults;

So basically when you have multiple -> you are just chaining from one object, to the next, to the next, etc.

Does that help?

On PHP, you can access values setted on attributes or get return of methods using -> (if they returning something [of course]).

Example:

<?php

class Car
{
    public function __construct()
    {
        $this->carColors = new Colors();
    }

    public function colors()
    {
        return $this->carColors;
    }
}

class Colors
{
    protected $availableColors = array('blue', 'red', 'green', 'black', 'white', 'yellow');

    public function randColor()
    {
        return $this->availableColors[array_rand($this->availableColors)];
    }
}

$car = new Car;
$randomColors = $car->colors()->randColor();
var_dump($randomColors);
1 Like

I didn’t understand it. Sorry :confused:

class Result {
    public $orderResult;
}
class OrderResult {
    public $shipmentResponses;
}
class ShipmentResponses {
    public $faults;
}
$shipmentResponses = new ShipmentResponses();
$shipmentResponses->faults = 'The Faults';

$orderResult = new OrderResult;
$orderResult->shipmentResponses = $shipmentResponses;

$result = new Result();
$result->orderResult = $orderResult;

echo $result->orderResult->shipmentResponses->faults;
2 Likes

What would happen if an intermediate result returned Null?

I would prefer validating a result before proceeding.

Hum, you can work defining defaults values on constructor method. But I agree how is a bad pattern create cascade on object properties.

1 Like

Indeed, you should not chain like this. In this case it seems the objects are mere DTOs so it doesn’t matter as much, but when creating objects with behaviour and such you should always keep in mind the law of Demeter.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.