Search code examples
phpclassclass-designextends

PHP Classes Extend


I have two classes that work seperate from another, but they extend the same class. Is it possible to have them work the same instance of the extended class. I'm wanting the constructor of the extended class to run only once.

I know this isn't right but something like this:

<?php
$oApp = new app;
class a extends $oApp {}
class b extends $oApp {}

Solution

  • Ah, in that case I believe you would want to pass the class in as a parameter for the other two classes:

    /**
     * 
     */
    class abParent{
        /**
         * @var app
         */
        protected $app;
        /**
         *
         * @param app $app
         */
        public function __construct(app &$app){
            $this->app = &$app;
        }
    }
    
    class a extends abParent{}
    class b extends abParent{}
    
    
    $app = new app();
    $a = new a($app);
    $b = new b($app);
    
    var_dump($a, $b);