简体   繁体   中英

PHP: Inheritance and Instance properties

This may be a trivial question, but I'm new to php and so please help me understand some of the basic concepts. Following is my question:

I create a class A and for another class B, I inherit A, such that: class B extends A . Now for class AI need to have only one instance running anytime. So I achieve this by:

class A {
        private static $instance = NULL;

        static public function getInstance()
        {
                if (self::$instance === NULL)
                        self::$instance = new x();
                return self::$instance;
        }
...
}

and then calling from program:

$a = A::getInstance();

Now someplace in main program and also in class AI need to declare an object for B. Such that:

$b = new B();

What I want to achieve now is for $b to inherit all the properties of class A that are set in A's only existing instance. For now its not happening that way. Please suggest! Will defining a constructor for class A with logic same as function getInstance() help?

Try something like this in B constructor:

__construct(){
    $toCopy = A::getInstance();
    $this->setAttribute1($toCopy->getAttribute1());
    $this->setAttribute2($toCopy->getAttribute2());
    ...
}

However maybe you don't even need A :

Class B{

    private static $_attr1;
    private static $_attr2;

    public static function getAttr1(){
        return self::$_attr1;
    }

    public static function getAttr1(){
        return self::$_attr1;
    }

}

Couple ways you might achieve this.

Singleton

It might be easier to delegate a lot of the inheritance internally, in order to ensure a singleton pattern. Simply load the singleton A object in class B, and reference it's properties and methods via the magic methods.

class B {
    function __construct()
    {
        $this->singletonObj = A::getInstance();
    } 
    function __get($field)
    {
        return $this->singletonObj->$field;
    }
    function __call($func, $args)
    {
        return call_user_func_array(array($this->singletonObj, $func), $args);
    }
    ....
}

Static Properties

Define class A with static properties.

class A {
    protected static $var = null;
    ....
}
class B extends A {
.... // has all the same static values as A
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM