PHP Design Patterns PHP OO This and Parent Basics
PHP This and Parent Basics
Here are examples of using this and parent to call functions in a class. Using $this-> a class calls functions in itself, using parent:: a class calls functions in it's parent class.
If you are used to Java or other OO languages you might expect parent:: to be $super->, but with PHP it is not. Maybe super wasn't used to avoid confusion with superglobals. I don't know why :: is used instead of -> for non static calls.
OOPHPParentClass.php
//copyright Lawrence Truett and FluffyCat.com 2007, all rights reserved
//OOPHPParentClass - a simple OO PHP Class which is extended by OOPHPChildClass class OOPHPParentClass { public function getColor() { return 'RED'; }
}
download source, use right-click and "Save Target As..." to save with a .php extension.
OOPHPChildClass.php
//copyright Lawrence Truett and FluffyCat.com 2007, all rights reserved
//OOPHPClass - a simple OO PHP Class which extends OOPHPParentClass
include_once('OOPHPParentClass.php');
class OOPHPChildClass extends OOPHPParentClass {
public function getColor() { return 'BLUE'; } public function getParentColor() { return parent::getColor(); }
}
download source, use right-click and "Save Target As..." to save with a .php extension.
testOOPHPThisParent.php
//copyright Lawrence Truett and FluffyCat.com 2007, all rights reserved
include_once('OOPHPChildClass.php');
define('BR', '<'.'BR'.'>');
echo 'TESTING OOPHPThisParent'.BR; echo BR; $childClass = new OOPHPChildClass(); echo 'test 1 - show the child color'.BR; echo $childClass->getColor(); echo BR.BR;
echo 'test 1 - show the parent color'.BR; echo $childClass->getParentColor(); echo BR.BR;
echo 'END TESTING OOPHPThisParent'.BR;
download source, use right-click and "Save Target As..." to save with a .php extension.
output of testOOPHPThisParent.php
TESTING OOPHPThisParent
test 1 - show the child color BLUE
test 2 - show the parent color RED
END TESTING OOPHPThisParent
References
Design Patterns
Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides
PHP 5
The Official PHP web site
Core PHP Programming, 3rd Edition by Leon Atkinson and Zeev Suraski
| Comments |
| Sign in to be the first to comment on PHP Design Patterns PHP OO This and Parent Basics. |