Question

I have a recursively defined function called getPropertyValue($object, $property) that returns false if $property doesn't exist at an arbitrary depth into $object, and the value corresponding to the first $property found inside $object otherwise. It is essentially a generalized version of PHP's built-in function property_exists()

I want to make this method chainable, and I know that to do this, I would simply return a reference to the class instance ($this) in the method, but I am already returning, as I mentioned above, the value corresponding to the first $property found inside $object.

How can I make this method chainable while still returning this value? I'm thinking a possibility is to return an object containing both $this and the value of that property/false, if it is found/not found, respectively. Is this a viable approach? What would be the best way to achieve chainability in this context?

Thanks very much.

Was it helpful?

Solution

This kind of API doesn't really work when you want to return data.

It can be a convenience for building complex objects where numerous methods can be executed with less boilerplate code. The methods tend to be named descriptively, giving a good idea of what being done.

An example is the 'query builder' pattern, building the SQL statement via chained methods.

$sql = $qb->select()->from('table')->where()->field('foo')->equals('bar');

Don't be fooled however, this is just saving you from using setters.

$qb->setSelect();
$qb->setFrom('table');
$qb->setField('foo');  
$qb->setEquals('bar');

Obvious you are not creating a query builder, and there are different implementations of the same API, however the key is they all add data to the object rather than return it.

OTHER TIPS

you can return multiple values by putting them into an array:

return array($value,$this); // so you return both.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top