Based on PHP5.3
Classes in PHP and their instances:
| The code is as follows |
Copy Code |
|
Class myclass{
Public $prop = 123;
}
$obj = new Myclass (); |
The member properties of a class (a property's salutation relative to the method) include class constants and class variables. Where the class constants are not nullable when defined, the properties of the class are assigned when they are defined, using only scalar arrays and cannot be expressions, because class attributes are initialized at compile time and PHP does not execute expressions at compile time.
1, the member's access control:
Public: Can be inherited, can be accessed outside the class's method, such as $obj->prop;
Protected: Can be inherited and cannot be accessed outside the class's method
Private: cannot be inherited, cannot be accessed outside the class's methods
PHP 4 uses Var to declare the properties of a class, which is no longer used after PHP5, PHP5.3 used before, and PHP5.3 can be used before or used as public alias.
These three access control keywords can also modify constructors, and when private and protected modify the constructor of a class, you can only invoke the constructor by using a static, Publice method to instantiate the object, because it is enough that the function cannot be accessed outside the class, for example, Implementation of a single instance class:
| The code is as follows |
Copy Code |
|
Class Singleton {
private static $instance =null;
Public $k = 88;
Private Function __construct () {
}
public static function getinstance () {
if (self:: $instance ==null) {
Self:: $instance = new self ();
}
Return self:: $instance;
}
Public Function __clone () {//pretend clone Oprationg
Throw (' Singleton class can not be cloned ');
return Self::getinstance ();
}
}
New Singleton (); Error
$in = Singleton::getinstance ();
|
2, inheritance prohibition: final keyword, only used to modify the class or class methods
If a class is final decorated, this class cannot be inherited, and if a method is final decorated, this method cannot be overridden by a quilt (override).
| The code is as follows |
Copy Code |
|
Class myclass{
Public $prop = 123;
Final public static function MethodA () {//non-inheritable, exposed static method
Return ' Here's a final method ';
}
} |
3. Abstract classes and abstract methods: Abstract for classes and methods only, abstract classes cannot be used directly for instantiating objects only for generating subclasses
| The code is as follows |
Copy Code |
|
Abstract class myclass{
Public $prop = 123;
Abstract public Function MethodA (); The abstract method does not implement the function body
} |