0

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.

Jay
  • 147
  • 3
  • 11
  • possible duplicate of [How do I chain methods in PHP?](http://stackoverflow.com/questions/7549423/how-do-i-chain-methods-in-php) – RafH Nov 03 '13 at 00:44
  • 2
    You return false. Chaining would mean to continue; and if false is returned from one method then why continue and return another value, if it failed? – AbraCadaver Nov 03 '13 at 00:54

2 Answers2

0

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

return array($value,$this); // so you return both.
Adriana
  • 91
  • 3
  • Yes, but in the context of the question, that's sloppy. They are expecting to chain methods with one end result or get false. Should we code to accept an array from all methods in case something in the chain is false but we want some value anyway? – AbraCadaver Nov 03 '13 at 00:56
  • okay, then you have to take another approach: only return $this and have the function write its results to an extern associative array with key names = property names and values = property value if found and false otherwise. then examine the array later after function has done its work. – Adriana Nov 03 '13 at 01:11
0

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.

AlexP
  • 9,906
  • 1
  • 24
  • 43