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

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -