Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Language Reference : Classes and Objects (PHP 4) : parent

parent

You may find yourself writing code that refers to variables and functions in base classes. This is particularly true if your derived class is a refinement or specialisation of code in your base class.

Instead of using the literal name of the base class in your code, you should be using the special name parent, which refers to the name of your base class as given in the extends declaration of your class. By doing this, you avoid using the name of your base class in more than one place. Should your inheritance tree change during implementation, the change is easily made by simply changing the extends declaration of your class.

<?php
class A {
function
example() {
echo
"I am A::example() and provide basic functionality.<br />\n";
}
}

class
B extends A {
function
example() {
echo
"I am B::example() and provide additional functionality.<br />\n";
parent::example();
}
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>

Related Examples ( Source code ) » keyword.parent











Code Examples / Notes » keyword.parent

mwwaygoo

With the example given previous from johnremovethreewordsplatte@pobox.com
You should only do this if your initialisation is different (no point in extending if it isn't)
When you extend a class its constructor still remains valid and is executed when constructed.  Writing a new constructor in the extended class overwrites the old one - inheritance.
so the following will also work
class Superclass {
function Superclass($arg) {
$this->initialize($arg);
}
function initialize($arg) {
$this->setArg($arg);
}
}
class Subclass extends Superclass {
//initialize() is inherited:
//BUT so is constructor
function extra_stuff($arg) {
echo "extra stuff " . $arg;
}
}
THE constructor is the function who's name is the same as the class that it is defined within.
AND remains the constructor even in extended classes, until redefined.
Think of the constructor as a seperate function from all the others.  As if PHP looks at your class and makes a copy of the function of the same name as the class and calls it "Constructor".
You can also create a function within the extended class with the same name as the constructor in the parent class without re-writing the constructor.  Because you are not altering the "Constructor" function.
(BUT any redefined variables are used in the constructor, as expected)
ie
class One
{
 var $v = "one";
 function One()
 {
   print "Class One::Constructor value=" . $this->v . "<br />\n";
 }
}
class Two extends One
{
 var $v = "two";
 function one()
 {
   print "REDEFINED : Class Two::Function One value=" . $this->v . "<br />\n";
 }
}
$o = new One();
$o->one();
$p = new Two();
$p->one();
results in :-
Class One::Constructor value=one
Class One::Constructor value=one
Class One::Constructor value=two
REDEFINED : Class Two::Function One value=two


aid

With regard to the chaining of Constrcutures, surely this is a simple and replaible method..?
<?php
class A
 {
 function A()
   {
   print "Constructor A
\n" ;
   }
 }
 
class B extends A
 {
 function B()
   {
   parent::A () ;
   print "Constructor B
\n" ;
   }
 }

class C extends B
 {
 function C()
   {
   parent::B ();
   print "Constructor C
\n" ;
   }
 }
 
$o = new C;
?>
Which outputs,
Constructor A
Constructor B
Constructor C


minoc

w/ PHP 4.0.5, I was able to chain
my constructors easily with:
class foo extends bar {
 function foo() {
   $par = get_parent_class($this);
   $this->$par();
   // then normal constructor stuff.
   // ...
 }
}


anonymous

Um, reading through all the gyrations on getting C++ constructor
semantics from PHP, I am wondering if I am just blindly missing something
when I use:
class A {
   function A () {  echo "A Constructor\n"; }
}
class B extends A {
   function B () { $this->A (); echo "B Constructor\n"; }
}
class C extends B {
   function C () { $this->B (); echo "C Constructor\n"; }
}
$c = new C ();
produces:
A Constructor
B Constructor
C Constructor
I'm new to PHP, but it seems to me that this is simpler and cleaner
than the solutions discussed here, with the only disadvantage being that
when you change the name of your superclass you have to change one
line in your subclass.
What am I missing? Are there advanced PHP-OO considerations that
make this code undesireable??


seedpod23

This example might illustrate something which was unclear to me when using the $parent::method() syntax.
I didn't see any documentation on whether or not $this (object variables) would be available in the parent class method so I wrote this example:
class One {
 var $v = "one";
 function OneDo() {
   print "One::OneDo " . $this->v . "
\n";
 }
}
class Two extends One {
 function CallParent() {
   parent::OneDo();
 }
}
$o = new Two();
$o->CallParent();
The output is "One::OneDo one", happy day!


tim dot parkinson

There is an implication here that variables of the parent class are available.  You can't access variables using parent::

mazsolt

There is a difference between PHP and C# managing the overloaded variables of the parent class:
[PHP]
class a{
var $a=1;
function display(){
echo $this->a;
}
}
class b extends a{
var $a=9;
}
$x=new b;
$x->display(); // will display 9
The same code in C# will display the value from the parent class.
[C#]
class a{
private int a=1;
public int display(){
return this.a;
}
}
class b:a{
private int a=9;
}
b x = new b();
Response.Write(b.display()); // will display 1


lelegiuly

Sorry but my example above it's correct only if there's one class that inherits by another class. If the hierarchical tree is deeper than 2 my example doesn't work. The result is a infinite loop cycle.
Why? Because the only instanced object is the B class (in my example).
$this alwais refer to instanced object.
See also the "sal at stodge dot org" notes in 4 October 2002.


hustbaer

something on the note of 'minoc':
in this setup, the "$this->$par();" will lead to infinite recursion...
class foo extends bar {
 function foo() {
   $par = get_parent_class($this);
   $this->$par();
   // then normal constructor stuff.
   // ...
 }
 function bar()
 {
   echo "this makes no sense, but who cares :)";
 }
}
but the problem is easity fixed by going like so:
class foo extends bar {
 function foo() {
   $par = get_parent_class($this);
   parent::$par();
   // then normal constructor stuff.
   // ...
 }
 function bar()
 {
   echo "this makes no sense, but who cares :)";
 }
}


gibby

Regarding the example above, I believe the result is misleading, if you're inferring that the $this in Class One's OneDo method refers to One.
If that wasn't your conclusion, then my apologies-- I misunderstood you.
But if it was, it might save trouble to note that $this is effectively an alias for $o (a Class Two object).  $v is available to $o, and that's how it's being picked up.  $this is $o in that example, not One (One is a class and has no implementation).
I hope that's helpful.
Brad


andyfaeglasgowtake_me_out

re: referring to a parents variables
The documentation doesn't say anything about how one should refer to the variables of a parent class in a child class (maybe it's obvious but I thought I'd point it out anyway).
class Actress {
var $bust;

function Actress() {$this->bust = "32C";}
function show() {echo "Bust: $this->bust...";}
}
class HollywoodActress extends Actress{
var $attitude;

function HollywoodActress () {
$this->Actress();
$this->attitude = "Fiery";
}

function show() {
parent::show();
echo "Attitude: $this->attitude";
}

function modify_bust() {
$this->bust = "32DD";
}
}
$girl_at_theatre = new Actress();
$girl_at_theatre->show();
//output: "Bust: 32C..."
$object_of_gossip = new HollywoodActress();
$object_of_gossip->modify_bust();
$object_of_gossip->show();
//output: "Bust: 32D:...Attidude: Fiery"


ckrack

Note that we can use $this in the parent's method like we might expect.
It will be used as the instance of the extended class.
<?php
class foo {
   var $x;
   function foofoo()
   {
       $this->x = "foofoo";
       return;
   }
}
class bar extends foo {
   // we have var $x; from the parent already here.
   function barbar()
   {
       parent::foofoo();
       echo $this->x;
   }
}
$b = new bar;
$b->barbar(); // prints: "foofoo"
?>


james sleeman

It should be noted that when using parent:: you are able to call a method defined within the parent, or any class that the parent is extending.. for example.
<?php
 class A
 {
   function test()
   {
     echo 'Hello ';
   }
 }
 
 class B extends A
 {
   
 }
 
 class C extends B
 {
   function test()
   {
     parent::test();
     echo 'Bobby.';
   }
 }
 
 $D =& new C();
 $D->test();
?>
Outputs "Hello Bobby.", the fact that B does not define test() means that A's test() is called, it should also be noted that test() is called in the context of an 'A' class, so if you try and call parent:: in A's test() it will correctly fail.
It's also worth noting that parent:: also works fine in a static method, eg <?php  C::test(); ?> still outputs "Hello Bobby.", and you can even do <?php B::test(); ?> which correctly outputs "Hello ", even though we're calling a static method that lives in an ancestor class!


adrian dabrowski

if you like to use the here suggested method of calling a parent constructer by using get_parent_class(), you will expirience undesired behaviour, if your parent is using the same technique.
class A {
 function A() {
    $me = get_class($this);
    echo "A:this is $me, I have no parent\n";
 }
}  
class B extends A {
 function B() {
    $par = get_parent_class($this);
    $me = get_class($this);
    echo "B:this is $me, my parent is $par\n";
   
    parent::$par();
 }
}  
class C extends B {
 function C() {
    $par = get_parent_class($this);
    $me = get_class($this);
    echo "C:this is $me, my parent is $par\n";
   
    parent::$par();
 }
}  
new C();
this will not produce the output you probably expected:
C:this is c, my parent is b
B:this is b, my parent is a
A:this is a, i have no parent
...but insted you will get in serious troubles:
C:this is c, my parent is b
B:this is c, my parent is b
Fatal error:  Call to undefined function:  b() in .............. on line 16
$this is always pointing to the 'topmost' class - it seems like this is php's way to cope with polymorphic OOP.


lelegiuly

If you like Java and you have to call parent constructor, this is my method:
class object {
  function super() {
    $par = get_parent_class($this);
    $this->$par();
  }
}
class A extends object {
  function A() {
    echo "A constructor\n";
  }
}
class B extends A {
  function B() {
    $this->super();
    echo "B constructor\n";
  }
}
Include the classes above, instance a new B class and this is the output:
A constructor
B constructor
In your web application every class will extend the object class.
Good luck, Emanuele :)


venome

If you have a complex class hierarchy, I find that it's a good idea to have a function constructor() in every class, and the 'real' php constructor only exists in the absolute base class.
From the basic constructor, you call $this->constructor(). Now descendants simply have to call parent::constructor() in their own constructor, which eliminates complicated parent calls.


horne

I've been scouring through the comments but haven't been able to find an example of how to use variable overriding. The manual hints that it is possible, but there aren't any examples. See the code for what I want to do:
class A {
 var $x;
 function A() {
   $this->x = 32;
 }
 function joke() {
   print "A::joke" . A::x . "
\n"; # SYNTAX ERROR!!
 }
}
class B extends A {
 var $x;
 function B() {
   parent::A();
   $this->x = 44;
 }
 function joke() {
   parent::joke();
   print "B::joke " . $this->x . "
\n";
 }
}
I want the following output when I call B::joke:
A::joke 32
B::joke 44
what do I get if I replace the A::x with $this->x?
A::joke 44
B::joke 44
How do I set the variable $x in the base class? Or, how do I get $this to point to the part of the class that is owned by class A?
I've tried the following (quite invalid) syntaxes:
A::x
A::$x
${A::x}
A::{$this->x}
It'd be nice to have a concrete example of how to access (read and write) parent variable members, or explicitly say that it is not possible to do that.


dan

I agree with "anonymous coward". That syntax seems silly in a constructor and only results in an extra function being called. The only time the parent will ever change is if you change the extends expression in your class definition.
However, the parent:: syntax is very useful when you need to add extra functionality to a method of a child class which is already defined in the parent class.
Example:
class foo {
  var $prop;
  function foo($prop = 1) {$this->prop = $prop;}
  function SetProp($prop) {$this->prop = $prop;}
}
class bar extends foo {
  var $lastprop;
  function bar($prop = NULL) {
     is_null($prop) ? $this->foo() : $this->foo($prop);
  }
  function SetProp($prop) {
     $this->lastprop = $this->prop;
     parent::SetProp($prop);
  }
}


php

Here is the workaround I came up with based on the comments about using a 'constructor' method and the parent:: syntax...
#cat test.php
<?php
class foo {
 function foo() { $this->constructor(); }
 function constructor() {
   echo get_class($this)." (foo)\n";
 }
}
class bar extends foo {
 function bar() { $this->constructor(); }
 function constructor() {
   echo get_class($this)." (bar)\n";
   parent::constructor();
 }
}
class baz extends bar {
 function & baz() { $this->constructor(); }
 function & constructor() {
   echo get_class($this)." (baz)\n";
   parent::constructor();
 }
}
$o = new baz;
?>
#php test.php
X-Powered-By: PHP/4.1.2
Content-type: text/html
baz (baz)
baz (bar)
baz (foo)
#
--
'a' -> 'o' in email TLD


johnremovethreewordsplatte

Combining the above suggestions with the "Pull Up Constructor Body" refactoring from Fowler (http://www.refactoring.com/catalog/pullUpConstructorBody.html), I found an elegant way to inherit constructors in PHP. Both superclass and subclass constructors call an initialize() method, which can be inherited or overridden. For simple cases (which almost all of mine are), no calls to parent::anything are necessary using this technique. The resulting code is easy to read and understand:
class Superclass {
   function Superclass($arg) {
       $this->initialize($arg);
   }
   function initialize($arg) {
       $this->setArg($arg);
   }
}
class Subclass extends Superclass {
   function Subclass($arg) {
       //initialize() is inherited:
       $this->initialize($arg);
   }
}


joan

But if we are not using extends but instead want to know who instantiated the class.
class A {
foo(){
// aviously this do not work but how would need to be changed
echo parent::foo;
}
class B {
$foo = 'test';
myObject = new A();
myObject.foo();
}


riku dot tuominen

But if we are not using extends but instead want to know who instantiated the class.
class A {
foo(){
// aviously this do not work but how would need to be changed
echo parent::foo;
}
class B {
$foo = 'test';
myObject = new A();
myObject.foo();
}


komashooter

An example for using a memberfunction with another memberfunction.
The sequencing for the creating of the class is important.
<?php
class A
{
  function example()
  {
      echo "I am A::example() and provide basic functionality.
\n";
  }
}
class B extends A
{
  function example()
  {
      echo "I am B::example() and provide additional functionality.
\n";
      parent::example();
  }
}
class C extends A
{
 
  function example()
  {
    global $b;
      echo "I am c::example() and provide additional functionality.
\n";
      parent::example();
  $b->example();
  }
}
$b = new B();
$c = new C();
$c->example();
;?>
Result:
I am c::example() and provide additional functionality.
I am A::example() and provide basic functionality.
I am B::example() and provide additional functionality.
I am A::example() and provide basic functionality.


27-may-2004 06:40

About the constructors :
Yes, a good pratrice could be to use a method called by the real constructor. In PHP 5, constructor are unified with the special __construct method. So we could do :
<?php
class A {
   var $a = "null";
   function A() {
       $args = func_get_args();
       call_user_func_array(array(&$this, "__construct"), $args);
   }
   function __construct($a) {
       $this->a = $a;
       echo "A <br/>";
   }
}
class B extends A {
   var $b = "null";
   function __construct($a, $b) {
       $this->b = $b;
       echo "B <br/>";
       parent::__construct($a);
   }
   function display() {
       echo $this->a, " / ", $this->b, "<br/>";
   }
}
$b = new B("haha", "bobo");
$b->display();
?>
It will have the same behavior than standard php constructors, except that you can not pass arguments by reference.


sal



When using the technique suggested by "<b>minoc at mindspring dot com</b>" on this page - USE EXTREME CAUTION.
The problem is that if you inherit of a class that uses this kludge in the constructor you will end up with a recursive constructor - unless that new class has a constructor of it's own that by-passes the kludged constructor.
What I am saying, is you can use this technique as long as you can ensure that each class you inherit from a class containing this technique in the constructor has a constructor class of it's own that does not call the parent constructor...
On balance it is probably easier to specify the name of the constructor class explicitly!
If you make this mistake the symptoms are pretty easy to spot - PHP spirals into an infinitely recursive loop as soon as you attempt to construct a new class. Your web-server will returns an empty document.


bitmore.co.kr

/* Original */
/*
class A {
var $x;
function A() { $this->x = 32; }
function joke() { print "A::joke" . A::x . "
\n"; # SYNTAX ERROR!! }
}
class B extends A {
var $x;
function B() {
parent::A();
$this->x = 44;
}
function joke() {
parent::joke();
print "B::joke " . $this->x . "
\n";
}
}
echo A::joke();
echo B::joke();
*/
/* Original */
/* Modify */
/*
class A {
var $x;
function A() { $this->x = 32; }
function joke() {
$this = new A;
print "A::joke = " . $this->x . "
\n";
}
}
class B extends A {
var $x;
function B() {
parent::A();
$this->x = 44;
}
function joke() {
parent::joke();
$this = new B;
print "B::joke = " . $this->x . "
\n";
}
}
echo A::joke();
echo B::joke();
//print Show
A::joke = 32
A::joke = 32
B::joke = 44
*/


10-mar-2007 11:49

<?php
   class A {
     function X() {
       echo 'y';
     }
   }
   
   class B extends A{
     function X() {
       echo 'z';
     }
     
     function Y() {
       echo parent::X();
     }
   }
   
   class C extends B {
     function Z () {
       echo parent::Y();
     }
   }
$c = new C();
$c->Z();                  //output is 'y'
?>


Change Language


Follow Navioo On Twitter
class
extends
Constructors
Scope Resolution Operator (::)
parent
Serializing objects - objects in sessions
The magic functions __sleep and __wakeup
References inside the constructor
Comparing objects
eXTReMe Tracker