This article provides a detailed analysis of the static keywords and class constants in php. if you need a friend, please refer to the OO information of PHP, access control modifier, self, parent, const, static several keywords, arrow operator (this is also called in the book .. "->"), range resolution operator (double colon ":"), but I think this is the same as many OO in C # language, it's easy to understand, but let's take a look at how to clarify the OO ideas in PHP.
--------------------------------------------------------------------------------
Declare static class members and methods so that they do not need a class instance. the declaration of a static member cannot be accessed through an instance of a class object (although a static method is acceptable ).
The static declaration must follow the visibility declaration. To be compatible with PHP 4, if no visibility is declared, the members and methods will be deemed to have been declared as public.
Since static methods can call non-object instances, pseudo variable $ this cannot be used in declared static methods.
In fact, the static method call form is determined during compilation. When you use a class name that must be declared, the method fully identifies and applies without inheritance rules. When you use a class name that must be declared, this method is fully validated and the inherited rules are not used.
If self has been declared, self is interpreted by the current class. It does not apply to or inherit from rules. Static attributes cannot access non-static methods through the arrow operator->., which generates an E_STRICT-level warning.
The code is as follows:
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 ";
?>
The code is as follows:
// Static method example)
Class Foo
{Public static function aStaticMethod (){}
}
Foo: aStaticMethod ();
?>
You can define constants in each base class to keep them unchanged. When you do not use the $ symbol to declare or use it, constants are different from common variables. Like a static member, a constant value cannot be accessed through an instance of an object (instead, $ object: constant should be used ). a constant value must be a constant expression rather than a variable, a member of a class, a mathematical expression, or a function call result.
The code is as follows:
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
?>