Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Static Method from Class B(which extends Class A) of Class A

Tags:

oop

php

There was an interesting question in a practice test that I did not understand the answer to. What is the output of the following code:

<?php
class Foo {
    public $name = 'Andrew';

    public function getName() {
        echo $this->name;
    }
}

class Bar extends Foo {
    public $name = 'John';

    public function getName() {
        Foo::getName();
    }
}

$a = new Bar;
$a->getName();
?>

Initially, I thought this was produce an error because static methods can not reference $this (atleast in PHP5). I tested this myself and it actually outputs John.

I added Foo::getName(); at the end of the script and did get the error I was expecting. So, what changes when you call a static method from within a class that extends the class you're calling from?

Would anyone mind explaining in detail exactly what is going on here?

like image 343
Mike B Avatar asked Feb 05 '09 15:02

Mike B


People also ask

Can I call static method from another class?

Call a static Method in Another Class in Java In the case of a static method, we don't need to create an object to call the method. We can call the static method by using the class name as we did in this example to call the getName() static method.

How do you call a static method in inherited class?

A static method is the one which you can call without instantiating the class. If you want to call a static method of the superclass, you can call it directly using the class name.

Can static method be extended?

Can we override a static method? No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods.


2 Answers

Foo::getName() is using an older PHP4 style of scope resolution operator to allow an overridden method to be called.

In PHP5 you would use parent::getName() instead

It's useful if you want to extend, rather than completely override the behaviour of the base class, e.g. this might make it clearer

class Bar extends Foo {
    public $name = 'John';

    public function getName() {
        echo "My name is ";
        parent::getName();
    }
}
like image 60
Paul Dixon Avatar answered Sep 28 '22 14:09

Paul Dixon


If you call the static method bound to the other object, the method is executed in the context of the current object. Which allows access to the $this-object.

Better way to call the superclass-method from inside the subclass would be:

parent::getName();
like image 28
Ulf Avatar answered Sep 28 '22 14:09

Ulf