Mohammad Daud Ibrahim
Mohammad Daud Ibrahim

Reputation: 146

Why does PHP allow calling non-static methods statically but does not allow calling non-static properties statically?

Why does PHP allow calling non-static method statically using Class Names and by the various keywords such as self, static & parent which are placeholders for Class Names?


But on the other hand it does not allow calling non-static properties statically?


Here is the sample code -

<?php

 # PHP Version 7.1.7
 error_reporting(E_ALL);
 ini_set('display_errors', 1);

 class Fruit {
     public $name = 'Fruit';
     public function x() {
         echo "Fruit_x" . "<br>";
     }
 }

 class Orange extends Fruit {

     public $name = 'Orange';
     public function x() {
         echo "Orange_x" . "<br>";
         parent::x();
         self::y();
         static::z();

         // Code Below will throu Uncaught Error: Access to undeclared static property
         // echo parent::$name . "<br>";
         // echo self::$name . "<br>";

     }

     public function y(){
         echo "Y" . "<br>";
     }

     public function z(){
         echo "Z" . "<br>";
     }

 }


 (new Orange)->x(); // No Warnings

 Orange::x();  // However calling like this shows warning as of PHP 5 & 7
 // Docs - http://php.net/manual/en/language.oop5.static.php

?>

You can Run Code in the Browser to see the following Result

Expected Result

PHP Static Keyword Docs

Upvotes: 2

Views: 1992

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35367

Based on your comment, I believe your misunderstanding comes from the fact that you think parent:: and self:: are always used for making static calls.

Parent is used for accessing a parent method of any type and self is used to always use the current class method. Since methods can only be defined once, PHP can infer how these methods should be called.

https://3v4l.org/NJOTK will show an example of the difference between $this->call(), self::call(), and parent::call() when using inheritance. static:: is allowed but functionally equivalent to $this-> for instance methods.

The same behavior does not extend to properties. Instance properties do not support the same level of inheritance, they only inherit values on instantiation. You cannot access a parent's property, only one property exists on that instance. Therefore, non-static properties are always accessed using $this->property.

Upvotes: 3

Related Questions