The static keywords and class constants of OO in PHP are discussed

  • 2020-06-07 04:08:44
  • OfStack

Look at the access control modifiers, self,parent,const,static. The arrow operators. That is, "- > "), the range parsing operator (double colon "::"), but this is the same as OO in C# language, it is easy to understand, but let's look at the OO idea in PHP.
--------------------------------------------------------------------------------
Declare static class members and methods so that it does not require an instance of a class. Declarations for 1 static member cannot be accessed by an instance of a class object (although a static method can).
Static declarations must follow visibility declarations. To be compatible with PHP 4, if no visibility is declared, then members and methods are treated as if they have been declared as public.
Because static methods can call non-object instances, the dummy variable $this cannot be used in methods declared static.
In fact, the static method call form is determined at compile time. When using a class name that must be declared, the method is fully identified and uninherited. This method is fully validated when the class name that must be declared is used, and there are no rules for inheritance.
If self has been declared, self is interpreted by the class to which it currently belongs. Nor does the inheritance rule apply. Static properties cannot pass through the arrow operator - > . Accessing a non-static method will result in an E_STRICT level warning.


<?php
class Foo
{   public static $my_static='foo';
    public function staticValue(){   return self::$my_static;   }
}
class Bar extends Foo
{   public function fooStatic(){   return parent::$my_static;   }
}
print Foo::$my_static."/n";
$foo = new Foo();
print $foo->staticValue()."/n";
print $foo->my_static."/n";// Undefined "Property" my_static 
// $foo::my_static is not possible
print Bar::$my_static."/n";
$bar = new Bar();
print $bar->fooStatic()."/n";
?> 


// Static method instance (Static method example) 
<?php
class Foo
{   public static function aStaticMethod() {    }
}
Foo::aStaticMethod();
?> 

You can define constants in each base class to keep it constant. Constants are different from normal variables when you do not use the $sign to declare or use it. Like static members, a constant value cannot be accessed by an instance of an object (instead use $object::constant). A constant value must be a constant expression, not a variable, a member of a class, the result of a mathematical expression or function call.

<?php
class MyClass
{   const constant = 'constant value';
    function showConstant() {   echo  self::constant."/n";   }
}
echo MyClass::constant."/n";
$class = new MyClass();
$class->showConstant();// echo $class::constant; is not allowed
?>


Related articles: