PHP: class inheritance
Blogs20112011-09-07
For a large project, to compact, clear codes are very helpful for modifying, management and maintenance. The following is a snippet to make codes short, clear in a large project.
in a Parent-Children Class environment, instead of initializing varaibles in each sub-class, we refine the common varaibles in a higher classâ construct function, then using parent::_construct() to extend and instance when creating class. The following example illustrates the implementation: 1. in parent-class âBaseClass.inc.phpâ:
class BaseClass extends Smarty
{
var $url, $self, $session, ...;
function __construct() {
// do Smarty construct.
parent::__construct();
$this->url = $_SERVER["PHP_SELF"];
// will extend in each sub-class.
$this->self = basename($this->url, '.php');
// will be overwritten in each sub-classes when create instances.
$this->session = array(
'sql' => $this->self.'_sql',
'rows' => $this->self.'_rows',
'magic_sql' => $this->self.'_magic_sql',
);
...2. in sub-class âListBase.phpâ, in its construct() function, declares the class variables, then initialize:
require_once("BaseClass.inc.php");
class ListBase extends BaseClass
{
// decalre class variables.
var $url, $self, $session,;
// when initializing, executes parent construct.
function __construct() {
parent::__construct();
}
...This way, when this class initializes, parent::__construct() will guarantee all the variables: $url, $self, $session will point to âListBase.phpâ, not parent-class âBaseClass.phpâ.
3. in sub-sub-class âUsersClass.phpâ, the same way: declares the class variables, then initialize.
require_once("ListBase.php");
class UsersClass extends ListAdvanced
{
var $url, $self, $session;
public function __construct() {
parent::__construct();
}Remember, the declares is important, it indicates these variables are belong to this class, not parent class or anyplace else. Canât be ignored. This maybe the most compact way to extend sub-class with same varaibles(class properties) but different values. Very useful for multi-inheritances and lots of sub-classes with same parent class. For examples, a class has more than 20 sub-classes, using this will save codes.
