Page 1 of 1
How to get parent class's method call from child?
Posted: Thu Jun 28, 2007 1:32 am
by saumya
hi,
I believe PHP deals with classes the same way as other OOP programming languages.But surprisingly it does not, I hope. Here is a situation I came across, I have 2 classes "Controller" and "Controller_login" where
Code: Select all
class Controller_login extends Controller
There is a method in "Controller" named "getModel()", which I want to call from "Controller_login". To my surprise, if I call it directly as "getModel()", PHP throws an error. To solve this I am calling the method as
which solves my problem.
In a general OOP environment this should not have happened?!!
I am concluding that PHP has got this peculiar behaviour, so one has to live with it.
Please suggest whether my understanding is correct ?
thank you
Posted: Thu Jun 28, 2007 1:37 am
by John Cartwright
Code: Select all
class Controller_login extends Controller
{
public function __construct()
{
print_r($this->getModel());
}
}
class Controller
{
protected function getModel()
{
return array('foo' => 'bar');
}
}
$controller = new Controller_login();
//outputs Array ( [foo] => bar )
Not sure what you mean?
Posted: Thu Jun 28, 2007 3:51 am
by saumya
hi Jcart,
thanks for the reply.
I will try your method.
Previously I was a little confused as in other languages we just call method name, if we are calling from inside the same class and I have tried the same thing in my script and failed.I will keep in mind that if one has to call a method it has to be
not
Posted: Thu Jun 28, 2007 4:15 am
by Oren
In PHP: "$this->method()" and not "this->method()"

Posted: Thu Jun 28, 2007 5:19 am
by saumya
ohh yes, missed again.
But no way, only
always has to be
thanks
Posted: Thu Jun 28, 2007 6:58 am
by kyberfabrikken
Yes, in Java, the $this-> part is implicit. That isn't possible in PHP, because then you wouldn't be able to distinguish between global functions and member methods. Eg. the following would be ambiguous:
Code: Select all
function foo() {
}
class Bar
{
function foo() {
}
function doStuff() {
foo(); // does this refer to $this->foo() or the global function foo() ?
}
}
Posted: Thu Jun 28, 2007 7:17 am
by saumya
ohh yeah.That clears it all.
thank you so much guys.
Posted: Thu Jun 28, 2007 7:47 am
by stereofrog
kyberfabrikken wrote:Yes, in Java, the $this-> part is implicit. That isn't possible in PHP, because then you wouldn't be able to distinguish between global functions and member methods.
Well, that's not a problem in most languages: look for the method first, if not found, take a global function, that's simple. On the other side, this syntax may look confusing for beginners, perhaps this is the reason why it wasn't implemented.