php - Setting and using parameters from parent class -


is there way can write code this:

<?php  class baseclass {        public $testvar;      public function __construct ($testvar) {         $this->testvar = $testvar;     } }  class childclass1 extends baseclass { }  class childclass2 extends baseclass { }  $bc = new baseclass('test1'); $cc1 = new childclass1(); $bc->testvar = 'test2'; $cc2 = new childclass2();  echo $cc1->testvar; // should echo 'test1' echo $cc2->testvar; // should echo 'test2' ?> 

the reason asking don't have specify parameters every time create new child class. want make have specify parameters once (preferably when creating base class).

is possible?

it's point of object oriented programming every instance has it's own parameters.

but want use class once whole application. database controller or router. can use static properties , methods:

class baseclass {     public static $testvar;      public function __construct ($testvar) {         self::$testvar = $testvar;     } } 

note value of static $testvar same in objects. work around this:"

class baseclass {     public $testvar;     public static $test_var;      public function __construct ($testvar = '') {         if (!empty($testvar)) {             self::$test_var = $testvar;         }          $this->testvar = self::$test_var;     } }  class childclass1 extends baseclass { }  class childclass2 extends baseclass { }  $bc = new baseclass('test1'); $cc1 = new childclass1(); echo $cc1->testvar; // should echo 'test1'  baseclass::$test_var = 'test2'; $cc2 = new childclass2();  echo $cc1->testvar; // **should echo 'test1'** echo $cc2->testvar; // should echo 'test2' 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -