SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
Thread: OOP: $this or parent?
-
Dec 3, 2004, 06:51 #1
- Join Date
- Feb 2004
- Location
- Örebro, Sweden
- Posts
- 2,716
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
OOP: $this or parent?
Hi,
Which is the most correct way to access the methods of a parent class?
Should one use $this->method() or parent::method()?
Yours, Erik.
-
Dec 3, 2004, 07:51 #2
- Join Date
- Mar 2004
- Posts
- 1,647
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
i use zends double collon for accessing parent classes
cheers
-
Dec 3, 2004, 08:08 #3
- Join Date
- May 2004
- Location
- Germany
- Posts
- 550
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
take a look at this:
PHP Code:class father
{
var $foo = 'me';
function getFoo(){
return $this->foo;
}
}
class child extends father
{
function getme(){
return parent::getFoo();
}
function getFoo(){
return 'this is my Foo';
}
}
$child = new child();
echo '->'.$child->getFoo().'<br />';
echo '::'.$child->getme();
Code:->this is my Foo ::me
I always use $this->parentfunction(), but not for this reason, as i discovered it just now
I thought :: is for static calls, so i thought parent::getFoo() shouldn't return anything, but this would only bee if i'd use father::getFoo()
Do i make sense? nope, at least not to me
Edit:
I think parent::function makes only sense when used in the same function in the child class, e.g.
PHP Code:class child{
function foo(){
$ret = parent::foo();
/*
*do some calculations with $ret,
*that are not done in the parent class
*/
return $ret;
}
}
-
Dec 3, 2004, 09:39 #4
- Join Date
- Oct 2004
- Location
- Sutton, Surrey
- Posts
- 259
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Use $this->method() if you want the version in the subclass to be executed. If it has not been defined in the subclass it will cascade up to the superclass.
User parent::method() if you want to execute the version in the superclass and ignore the version in the subclass completely. A common example is parent::__construct() when you want to execute the parent's constructor as well as the child's constructor as PHP does not do this by default.
-
Dec 3, 2004, 09:41 #5
- Join Date
- Feb 2004
- Location
- Örebro, Sweden
- Posts
- 2,716
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Hi,
Thanks guys.
Yours, Erik.
Bookmarks