The best way to call optional method in PHP? -
How better it will be,
Check the existence of the method of getting started:
square fu times {public function __ composition () {. . If (is_callable ([$ obj, 'myMethod'])) {$ obj- & gt; MyMethod (); }. . }} or
b. Parent class has an empty method
class bar {secure function myMethod () {}} class foo bar {public function __ composition () {. . . $ Obj- & gt; MyMethod (); . . . }}
You never have to guess that an object is a method or not . You need to know whether the method is based on the type of object or not. You should either want its type, in general, you should have a sensible class hierarchy and need the right type in the appropriate places: function foo MyType $ bar ) {...} This function requires an object of class MyType , and you know that MyType and so on can not do. So there is no need to check anything.
However, in some circumstances you may have to manually check, in which case instanceof : if ($ foo instanceof MyType) {...} If that particular method is not well fit within a specific category hierarchy, create an interface for it:
Interface MyMethodInterface {public function myMethod (); } Check the above type against class Foo MyMethodInterface applied {public function myMethod () {...}} then MyMethodInterface .
Comments
Post a Comment