开发者

ignore non existing method

so let's say you have a singleton pattern or whatever:

class Smth{  
  public static function Foo(){
    static $instance;
    if(!condition()) return false; // <-- it's nothing...

    if(!($instance instanceof FooClass)) $inst开发者_运维问答ance = new FooClass();
    return $instance; // <-- it's a object and has that method
  }
}

so if I call Smth::foo()->A_foo_method() when condition() is met, then the method is executed and everything is OK.

But if condition() is not met, obviously I get a fatal error telling me that Smth::foo() is not a object etc...

How can I simply ignore the 2nd case.? I mean don't do anything, and don't show the fatal error.

(besides checking the condition() outside the class, when calling the method)


You do not want to do that. This is a silent failure and it's not a good thing. When you call a method, you expect it to do something (especially a getInstance-like method in the Singleton pattern, which should return an instance). So yes, you have to check if foo() returns an actual object before calling A_foo_method(). Silently failing instead could create a debugging mess.


Have a look at the Special Case pattern.


It's because you are returning false from Smth::foo(). This should return the instance of Foo so the rest of the chain can run.

I assume you're doing lazy loading of Foo. Take a look at the following simple example of doing the same with a DB object and see if it scales.

private static $dbh;

public static function DBC() {
    if (self::$dbh === null) {
        self::$dbh = new mysqli($mysql['host'], $mysql['un'], $mysql['pw'], $mysql['db']);
    }

    return self::$dbh;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜