2

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.