PHP: access a parent's static variable from an extended class' method

Asked
Active3 hr before
Viewed126 times

8 Answers

parentclassvariablestaticaccess
90%

Still trying to figure out oop in PHP5. The question is, how to access a parent's static variable from an extended class' method. Example below.,But in this case you can access it both with self::$base_url and static::$base_url - as you don't redeclare this property in the extending class. Have you done it so, there would have been a distinction:, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,It's completely irrelevant that the property is declared in the parent, you access it the way you access any static property:

It's completely irrelevant that the property is declared in the parent, you access it the way you access any static property:

self::$base_url

or

static::$base_url // for late static binding
load more v
88%

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. These can also be accessed statically within an instantiated class object. , It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self, parent and static). , Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside methods declared as static. , Static properties are accessed using the Scope Resolution Operator (::) and cannot be accessed through the object operator (->).

foo
foo

Notice: Accessing static property Foo::$my_static as non static in /in/V0Rvv
on line 23

Warning: Undefined property: Foo::$my_static in /in/V0Rvv
on line 23

foo
foo
foo
foo
72%

I have a base class that I need to call functions on a class that is referenced in the child class.,What I wanted to do was just set reference as a static property on the extended_class class.,Now the reference is different for each class that extends base_class.,What happens when we declare the reference with each child class.. most of the time?

Easy enough,

class base_class {

   public
   function doSomethingWithReference() {
      $this - > reference - > doSomething();
   }
}

class extended_class extends base_class {

   protected $reference;

   public
   function __construct($ref) {
      $this - > reference = $ref;
   }
}
load more v
65%

This is because variable overriding might break methods inherited from the Parent if we change its type in the Child class.,The Child class's object contains both variables (one inherited from the Parent class and another declared in Child itself) but the child class variable hides the parent class's variable.,Well generally, we say that the Child class will override the variable declared in the Parent class, and parent.x will give us whatever the Child's object is holding. Because it is the same thing, it happens while we do the same kind of operation on methods.,And as mentioned, if Java allows variable overriding, then the  Child's variable cannot substitute the  Parent's variable, and this would break the Liskov Substitutability Principle (LSP).

In order to understand this, let us consider the example below where we declare a variable x with the same name in both Parent and Child classes.

class Parent {
   // Declaring instance variable by name `x`
   String x = "Parent`s Instance Variable";

   public void print() {
      System.out.println(x);
   }
}

class Child extends Parent {

   // Hiding Parent class's variable `x` by defining a variable in child class with same name.
   String x = "Child`s Instance Variable";

   @Override
   public void print() {
      System.out.print(x);

      // If we still want to access variable from super class, we do that by using `super.x`
      System.out.print(", " + super.x + "\n");
   }
}
load more v
75%

Accessing a PHP static property outside the class do not necessiate the creation of an object; you just have to qualify it with the class name followed by the double colon :: operator, known formally as the scope resolution operator. , We declare a class called Relay consisting of a static variable $time, which is assigned the value 0. Static properties are defined inside a class using the static keyword. , The static property $time was actually created to store these incremental time values. We add the __construct() function to the Relay class above. , When a new object is created out of a class, it has a copy of the class's properties.

					<
					? php
					class Relay {
					   static $time = 0;
					} ?
					>
load more v
40%

You only need to use parent:: when accessing methods of the base class or static variables of the base class. If you try to access a non static variable of the base class you will get an error Access to undeclared static property" fatal error:,Or get rid of the static property and use instance variables and methods. Then you are not limited to one configuration of a particular type.,First off, Parent is a reserved word. Second off, don't use var unless you're using an older version of PHP. You can use protected. You don't need to use the parent keyword to access the variable because the child class should inherit it. You can access it via $this->myVar,The inner class (class2) is not associated with any specific instance of the outer class (class1). T access fields etc, you will need to first have an explicit reference to a class1 instance, probably passing it in via the constructor. For example, it could be:

Parent class

class ConfigBase {
   protected static $data = [];

   public static
   function Get($name) {
      if (!isset(self::$data[$name])) {
         return null;
      }

      return self::$data[$name];
   }

   public static
   function Set($name, $value) {
      self::$data[$name] = $value;
   }
}

Child class

class Database extends ConfigBase {
   protected static $data = [
      'host' => 'localhost',
      'username' => 'root',
      'password' => '',
      'database' => '',
      'port' => 3306
   ];
}

Output:

// NULL
echo Database::Get('host');
load more v
22%

Static methods can be accessed from outside the class using the class name and Scope Resolution Operator (::). (Only if the visibility is public), Static methods can be accessed from the methods in the same class using the self keyword and ::., Static methods can be called directly without needing an instance of the class (an object). And, $this pseudo-variable is not available inside static methods., In all the previous chapters, we created objects from classes before accessing methods and properties of it.

class MyClass {
   public static
   function myStaticMethod() {
      echo "Hyvor!";
   }
}
load more v
60%

When we have two classes where, one extends another and if, these two classes have same method including parameters and return type (say, sample) the method in the sub class overrides the method in the super class.,When superclass and subclass contains same method including parameters and if they are static. The method in the superclass will be hidden by the one that is in the subclass.,The key in method overloading is, if the super class and sub class have method with same signature, to the object of the sub class both of them are available. Based on the object type (reference) you used to hold the object, the respective method will be executed.,This mechanism is known as method hiding in short, though super and subclasses have methods with same signature it they are static, it is not considered as overriding.

Example

class Super {
   public static void sample() {
      System.out.println("Method of the superclass");
   }
}
public class OverridingExample extends Super {
   public static void sample() {
      System.out.println("Method of the subclass");
   }
   public static void main(String args[]) {
      Super obj1 = (Super) new OverridingExample();
      OverridingExample obj2 = new OverridingExample();
      obj1.sample();
      obj2.sample();
   }
}
load more v

Other "parent-class" queries related to "PHP: access a parent's static variable from an extended class' method"