user2086527
user2086527

Reputation: 11

PHP Chaining methods

class AAA

{

    function getRealValue($var)
    {
        $this->var = $var;
        return $this;
    }

    function asString()
    {
        return (string) $this->var;
    }

}

$a = new AAA;
$a->getRealValue(30); 
$a->getRealValue(30)->asString(); 

So when i call $a->getRealValue(30) it should return 30,

but when i call $a->getRealValue(30)->asString() it should return '30' as string'.

Thank you

Upvotes: 1

Views: 162

Answers (2)

Gordon
Gordon

Reputation: 316969

So when i call $a->getRealValue(30) it should return 30,but when i call $a->getRealValue(30)->asString() it should return '30' as string'.

This is not possible (yet). When getRealValue returns a scalar value, you cannot call methods on it.

Apart from that, your class makes little sense to me. Your method is called getRealValue but it accepts an argument and sets the value. So it should be called setRealValue. Method chaining aside, could it be are you looking for a ValueObject?

class Numeric
{
    private $value;

    public function __construct($numericValue)
    {
        if (false === is_numeric($numericValue)) {
            throw new InvalidArgumentException('Value must be numeric');
        }
        $this->value = $numericValue;
    }

    public function getValue()
    {
        return $this->value;
    }

    public function __toString()
    {
        return (string) $this->getValue();
    }
}

$fortyTwo = new Numeric(42);
$integer = $fortyTwo->getValue(); // 42
echo $fortyTwo; // "42"

Upvotes: 6

ewooycom
ewooycom

Reputation: 2721

Its not true, $a->getRealValue(30) will return object $a not value. But asString will return value in string format.

Usually when you want to get something like this you do:

$a->getRealValue(30)->get();
//Or
$a->getRealValue(30)->getAsString();

Upvotes: 3

Related Questions