FBP
FBP

Reputation: 345

PHP - Calling a static function from an object instance works?

I just wrote a sample class to better understand the static methods and variables in PHP. I understand how the static variables work but the static function is not working as expected. If you see the below code

class Car{
    static $wheels=4;
    static function getWheels(){
        echo Car::$wheels=10;
    }
}
$car1 = new Car();
$car1->getWheels();

I was expecting

$car1->getWheels(); to throw and error since getWheels is a static method.

Why is this not throwing an error or warning?

Upvotes: 2

Views: 34

Answers (1)

Moppo
Moppo

Reputation: 19275

I think it comes from the PHP 4 times, where there was no static keyword but you could call static methods whether with the -> or the :: operator

In fact, tecnically speaking, calling $car1->getWheels() was (and is) translated by PHP to Car::getWheels() at run time

With the advent of PHP5 this option was mantained for backward compatibility purposes

If you enable E_STRICT error reporting though, this should raise a warning now

Upvotes: 2

Related Questions