Section 3.10. parent:: and self::


3.10. parent:: and self::

PHP supports two reserved class names that make it easier when writing OO applications. self:: refers to the current class and it is usually used to access static members, methods, and constants. parent:: refers to the parent class and it is most often used when wanting to call the parent constructor or methods. It may also be used to access members and constants. You should use parent:: as opposed to the parent's class name because it makes it easier to change your class hierarchy because you are not hard-coding the parent's class name.

The following example makes use of both parent:: and self:: for accessing the Child and Ancestor classes:

 class Ancestor {     const NAME = "Ancestor";     function __construct()     {         print "In " . self::NAME . " constructor\n";     } } class Child extends Ancestor {     const NAME = "Child";     function __construct()     {         parent::__construct();         print "In " . self::NAME . " constructor\n";     } } $obj = new Child(); 

The previous example outputs

 In Ancestor constructor In Child constructor 

Make sure you use these two class names whenever possible.



    PHP 5 Power Programming
    PHP 5 Power Programming
    ISBN: 013147149X
    EAN: 2147483647
    Year: 2003
    Pages: 240

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net