PHP Functions Classes Methods Confusion
I am working on some legacy code at the moment and stumbled across a weird class/function call that php.net doesn't seem to explain and I've never seen before:
if(security::instance()->check_client()) {
There is a class security, and there are functions named instance and check_client inside that class. But this seems to call two functions in one statement and pass the one to the other, or at least thats what the outcome suggests. C开发者_如何学JAVAan someone clarify this one for me?
The execution goes like this:
- first, the static method
instance()
of thesecurity
class is executed - it returns an instance of the
security
class (most likely) - then, the
check_client
method is executed on the returned object
So, since security::instance()
is an object, you can call a method on it.
This is a classical implementation of the singleton pattern
I suppose your class security
looks like this :
class security {
private static $instance = null;
private function __construct() {}
public static function instance() {
if (null === self::$instance)
self::$instance = new security();
return self::$instance;
}
public function check_client() { /* do something */ }
}
What it does is that the static method instance returns an instance of the class security; Which mean that security::instance() instanceof security === true
That's why you can chain the call to the check_client() method as in your exemple
security::instance()->check_client()
This is similar to
$secu = security::instance();
$secu->check_client();
security:instance()
is a static call (so probably a static method)
http://php.net/manual/en/language.oop5.static.php
which returns an instance of some class, which has a member method check_client()
so it returns an object, then you can call any public method on that object.
I can only assume (as I don't know the underlying code), but it might explain it to you.
First of all functions can return objects. You then call an objects function on the returned object:
security::instance()->check_client()
Is the same like:
$securityInstance = security::instance();
$securityInstance->check_client();
Next to that, by the naming of instance
I would assume that security::instance()
returns the instance of the a security class, probably a singleton implementation or a factory based on the applications configuration.
精彩评论