继承static的注意点

继承static的注意点

singleton模式会使用

<?php
class Auth
{
    protected static $_instance = null;

    /**
     * 单用例入口
     *
     * @return Auth
     */
    public static function getInstance()
    {
        if (! self::$_instance) {
            self::$_instance = new self ();
        }
        return self::$_instance;
    }
}


class AuthV2 extends Auth
{

    // 使用父类的
    // protected static $_instance = null;

    /**
     * 单用例入口
     *
     * @return AuthV2
     */
    public static function getInstance()
    {
        if (! self::$_instance) {
            self::$_instance = new self ();
        }
        return self::$_instance;
    }

    public function checkLogin(){
        return false;
    }
}

Auth::getInstance();
AuthV2::getInstance()->checkLogin();

结果

上面的结果看上去感觉没有问题,但是...

// 出现如下错误
Fatal error: Call to undefined method Auth::checkLogin()

分析

  • 提示说使用的类竟然是Auth,而不是AuthV2,为什么?先看流程
  1. Auth::getInstance(); 给 Auth的$_instance赋值了。
  2. AuthV2::getInstance();返回的对象是直接使用父级Auth的$_instance,因此,没有再次执行new self()进行实例化。
  • 如果让Auth::getInstance() 再次实例化?
  1. AuthV2需要使用自己的 protected static $_instance = null;

正确代码:

<?php
class Auth
{
    protected static $_instance = null;

    /**
     * 单用例入口
     *
     * @return Auth
     */
    public static function getInstance()
    {
        if (! self::$_instance) {
            self::$_instance = new self ();
        }
        return self::$_instance;
    }
}


class AuthV2 extends Auth
{

    // 必须使用自身的
    protected static $_instance = null;

    /**
     * 单用例入口
     *
     * @return AuthV2
     */
    public static function getInstance()
    {
        if (! self::$_instance) {
            self::$_instance = new self ();
        }
        return self::$_instance;
    }

    public function checkLogin(){
        return false;
    }
}

Auth::getInstance();
AuthV2::getInstance()->checkLogin();
posted @ 2017-11-19 11:19  XIAOLI的博客  阅读(412)  评论(0编辑  收藏  举报