Constructor Clarification
Moderator: General Moderators
Constructor Clarification
Just need some clarification of the following from the PHP Manual:
"Note: Parent constructors are not called implicitly if the child class defines a constructor"
My perception is that if I do not define a constructor in the child, then the parent's will be called on a new instance of the child class. Is this assumption correct? If I define one in the child class, then I would have to call parent::__construct() as noted.
"Note: Parent constructors are not called implicitly if the child class defines a constructor"
My perception is that if I do not define a constructor in the child, then the parent's will be called on a new instance of the child class. Is this assumption correct? If I define one in the child class, then I would have to call parent::__construct() as noted.
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
*ponders*
so if we run these two lines in succession:
and we only have a _cconstruct in the class which is being extended, then have we just "reset" our parent class, or created an error? (I should really just type a few lines and test this myself..
so if we run these two lines in succession:
Code: Select all
$this->__destruct();
$this->__constuct();yeah feyd was right, didn't do anything special.. HOWEVER found something I never realised before..
you'll see a line called REFERENCE X
now I would have expected this call to __construct() from within __destruct() to call the __construct of egg, however nope.. it calls the __construct of shell.
here's the output returned
so the parent is calling a function from the class that extends it...
Code: Select all
<?
class egg {
public $somevar;
public function __construct() {
$this->somevar = 'egg __construct string';
}
public function __destruct() {
$this->somevar = 'egg __destruct string';
print_r("\n".$this->somevar."\n\n");
$this->__construct(); #REFERENCE X
}
}
class shell extends egg {
public function __construct() {
$this->somevar = 'shell __construct string';
}
}
$eggshell = new shell();
print_r($eggshell);
$eggshell->__destruct();
print_r($eggshell);
?>now I would have expected this call to __construct() from within __destruct() to call the __construct of egg, however nope.. it calls the __construct of shell.
here's the output returned
Code: Select all
shell Object
(
[somevar] => shell __construct string
)
egg __destruct string
shell Object
(
[somevar] => shell __construct string
)- superdezign
- DevNet Master
- Posts: 4135
- Joined: Sat Jan 20, 2007 11:06 pm
No it is not. When a class is extended, it's non-private functions and data become a part of the new class unless overwritten. So, $this->__construct() is called from the copy of __destruct() that belongs to shell, not from egg.nathanr wrote:so the parent is calling a function from the class that extends it...
Try making __destruct() private, then call it from the shell object.