parent

用户可能会发现自己写的代码访问了基类的变量和函数。如果派生类非常精炼或者基类非常专业化的时候尤其是这样。

不要用代码中基类文字上的名字,应该用特殊的名字 parent,它指的就是派生类在 extends 声明中所指的基类的名字。这样做可以避免在多个地方使用基类的名字。如果继承树在实现的过程中要修改,只要简单地修改类中 extends 声明的部分。

<?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;

// 这将调用 B::example(),而它会去调用 A::example()。
$b->example();
?>


add a note add a note User Contributed Notes
KOmaSHOOTER at gmx dot de
20-Dec-2004 09:59
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.<br>\n";
   }
}

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

class
C extends A
{
  
   function
example()
   {
         global
$b;
       echo
"I am c::example() and provide additional functionality.<br>\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.
28-May-2004 01: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.
andyfaeglasgowTAKE_ME_OUT at yahoo dot co dot uk
14-May-2004 11:15
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 at i-z dot de
06-May-2004 12:39
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"
?>
bitmore.co.kr
10-Feb-2004 05:13
/* Original */
/*
class A {
   var $x;
   function A() { $this->x = 32; }
   function joke() { print "A::joke" . A::x . "<br>\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 . "<br>\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 . "<br>\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 . "<br>\n";
   }
}

echo A::joke();
echo B::joke();

//print Show
A::joke = 32
A::joke = 32
B::joke = 44
*/
James Sleeman
10-Jan-2004 10:27
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
15-Sep-2003 10:48
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.
hustbaer
24-Aug-2003 01:37
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 :)";
  }
}
mazsolt at yahoo dot com
05-Jul-2003 06:04
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
horne at teradyne dot com
27-Mar-2003 12:09
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 . "<br>\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 . "<br>\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.
lelegiuly at iol dot it
25-Mar-2003 12:18
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.
lelegiuly at iol dot it
07-Mar-2003 12:46
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 :)
Dan
02-Mar-2003 09:03
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);
   }
}
anonymous at cowards dot com
08-Dec-2002 04:48
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??
aid at logic dot org dot uk
06-Dec-2002 04:27
With regard to the chaining of Constrcutures, surely this is a simple and replaible method..?

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

Constructor A
Constructor B
Constructor C
sal at stodge dot org
04-Oct-2002 12:57
<p>When using the technique suggested by "<b>minoc at mindspring dot com</b>" on this page - USE EXTREME CAUTION.</p>

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.
mwwaygoo at hotmail dot com
20-Sep-2002 11:54
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
johnremovethreewordsplatte at pobox dot com
13-Aug-2002 08:16
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);
   }
}
gibby at onebox dot com
15-Jun-2002 07:25
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
seedpod23 at hotmail dot com
30-May-2002 02:19
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 . "<br>\n";
  }
}

class Two extends One {

  function CallParent() {
   parent::OneDo();
  }
}

$o = new Two();

$o->CallParent();

The output is "One::OneDo one", happy day!
php at earthside dot arg
09-Apr-2002 01:41
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
minoc at mindspring dot com
08-Sep-2001 07:52
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.
   // ...
  }
}
tim dot parkinson at ntlworld dot com
28-Jul-2001 08:37
There is an implication here that variables of the parent class are available.  You can't access variables using parent::
venome at gmx dot net
25-Jun-2001 11:57
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.