php - How to safely chain methods? -


is there way "safely" chain methods in php , return null if previous method returns null? otherwise, error thrown: trying property on non-object;

for example, following code checks whether customer's phone number has changed using quickbooks sdk. don't have control on these methods.

$customer->getprimaryphone() return object since form wouldn't have been submitted otherwise, $old->getprimaryphone() may return null if no phone number existed previously.

the following required phone number:

$old->getprimaryphone()->getfreeformnumber()

if getprimaryphone() returns null, error thrown.

my question is: how avoid code repition in following case?

if (!empty($old->getprimaryphone())) {     if ($customer->getprimaryphone()->getfreeformnumber() !== $old->getprimaryphone()->getfreeformnumber()) {         // repetive code here     }    } else {         // repetive code here } 

i'd inclined implement equals method on phonenumber class (or whatever it's called). example

public function equals(phonenumber $othernumber) {     return $othernumber !== null && $this->getfreeformnumber() === $othernumber->getfreeformnumber(); } 

then can use

if (!$customer->getprimaryphone()->equals($old->getprimaryphone()) 

if you've got other logic needs applied (as indicated in comment arrays), can implement in equals method.


Comments

Popular posts from this blog

What Are The Best Universities In The World?

Hard vs. Soft Water: What's The Difference?

java - Solr query version issue: Invalid version or the data in not in 'javabin' format -