PHP Object-oriented basic knowledge points summary

Source: Internet
Author: User

Here is a summary of some of the PHP object-oriented basics, extracted from the PHP5.1 manual.

1. A variable member of a class is called "attribute", or "field", "characteristic", which is called "attribute" in this document.

2. The variables in the attribute can be initialized, but the initialized values must be constants, where the constants are constants when the PHP script is compiled, rather than the constants that are calculated at run time after the compilation phase.

3. Inside the member method of the class, you can access the properties and methods of the class by $this->property (property is the attribute name), but to access the static properties of the class or not in a static method, use self: $property.

4. Pseudo-variable $this can be used inside a non-static method of a class, which is an instantiated object reference that invokes the method

5. The value of a constant must be a fixed value, not allowed to be modified, and cannot be the result of a variable, class property, or other operation, such as a function call.     <?php class MyClass {Const constant = ' constant value '; function Showconstant () {echo self::constant.     "\ n"; }} Echo myclass::constant. "\ n"; $n =new MyClass (); $n->showconstant ();?>

6. The class of the constructor calls this method each time the object is created, so it is well suited to do some initialization work before using the object. If a constructor is defined in a subclass, the constructor for its parent class is not implicitly called. To execute the constructor of the parent class, you need to call Parent::__construct () in the constructor of the child class.

7. Destructors are removed when all references to an object are deleted or executed when an object is explicitly destroyed. The destructor of the parent class is not invoked secretly by the engine. To execute a destructor for a parent class, you must explicitly call Parent::__destruct () in the destructor body of the subclass. The destructor is called when the script is closed, at which point all header information is sent. Attempting to throw an exception in a destructor can result in a fatal error.

8. When you extend a class, subclasses inherit all the public and protected methods of the parent class. However, the methods of the subclass override the methods of the parent class.

9. Scope resolution operator (::), which can be used to access static members, methods, and constants when you access these static members, methods, and constants outside of a class, you must use the name of the class. The two special keywords, self and parent, are used to access members or methods within a class.

10. When a subclass overrides a method in its parent class, PHP no longer executes methods that have been overridden in the parent class until these methods are called in the subclass. This mechanism is also used for constructors and destructors, overloads, and magic functions.

11. Static variables and methods declare that class members or methods are static and can be accessed without instantiating the class directly. Static members cannot be accessed through an object (except static methods). Because static methods do not need to be called through an object, the pseudo-variable $this is not available in a static method. A static property cannot be accessed by an object through the operator. Using:: Calling a non-static method will result in an e_strict level error. Just like all other PHP static variables, a static property can only be initialized to a character value or a constant and cannot use an expression. So you can initialize a static property to an integer or an array, but you can't point to another variable or function return value, or point to an object.

12. If you do not specify visibility, the properties and methods are public by default.

13. Abstract class Abstract classes cannot be instantiated directly, you must first inherit the abstract class, and then instantiate the subclass. At least one abstract method should be included in the abstract class. If a class method is declared abstract, it cannot include a specific feature implementation. When inheriting an abstract class, the subclass must implement all the abstract methods in the abstract class, and the visibility of these methods must be the same (or looser) as in the abstract class. If an abstract method in an abstract class is declared as protected, then the methods implemented in the subclass should be declared as protected or public, not private. Application Example: Abstract class AbstractClass { //enforces that subclasses define these methods     abstract protected function getValue (); &nbs p;   Abstract protected function prefixvalue ($prefix);    //General method (non-abstract method)     Public Function PrintOut () {         Print $this->getvalue (). "\ n";    }} class ConcreteClass1 extends AbstractClass {    protected function GetValue () {&NB sp;       return "ConcreteClass1";    }     Public Function Prefixvalue ($prefix) {         return "{$prefix}concreteclass1";    }}

14. Using Interfaces (interface), you can specify which methods a class must implement, but you do not need to define the specifics of these methods. We can define an interface through interface, just like defining a standard class, but all of the methods defined in it are empty. All methods defined in the interface must be public, which is the attribute of the interface. To implement an interface, you can use the implements operator. All methods defined in the interface must be implemented in the class, or a fatal error will be reported. If you want to implement multiple interfaces, you can use commas to separate the names of multiple interfaces. When implementing multiple interfaces, the methods in the interface cannot have duplicate names. Interfaces can also be inherited by using the extends operator. Constants can also be defined in an interface. Interface constants and class constants are used exactly the same. They are all fixed values and cannot be modified by a quilt class or subinterface. Application Example://Interface Definition interface ITemplate {    public Function setvariable ($name, $var);     public function gethtml ($template); }//Use interface class Template implements ITemplate {    private $vars = Array ();       Publi C function SetVariable ($name, $var)     {        $this->vars[$ Name] = $var;    }       public function gethtml ($template)     {         foreach ($this->vars as $name + = $value) {             $template = Str_replacE (' {'. $name. '} ', $value, $template);        }           return $template;    }}

15.PHP5 provides the functionality of an iterative (iteration) object, just as with arrays, you can iterate through the properties of an object through foreach. By default, external iterations can only get the values of externally visible properties.     Application Example: <?php class MyClass {public $var 1 = ' value 1 ';     Public $var 2 = ' value 2 ';     Public $var 3 = ' value 3 ';     Protected $protected = ' protected var ';     Private $private = ' private var ';        function iteratevisible () {echo "myclass::iteratevisible:\n";        foreach ($this as $key + $value) {print "$key = = $value \ n"; }}} $class = new MyClass (); foreach ($class as $key + $value) {print "$key + $value \ n";} echo "\ n";

$class->iteratevisible ();?>

16. Design mode Factory mode (Factory) allows you to instantiate an object while the code is executing. It is called the Factory mode because it is responsible for the "production" object. The parameter of the factory method is the class name of the object that you want to generate. Singleton mode (Singleton) is used to generate a unique object for a class. The most common place is the database connection. Once an object is generated using singleton mode, the object can be used by many other objects. Application Example: <?php class Example {   //Save class instance in this attribute     private static $instance;   & nbsp       //Construction method declared private to prevent direct creation of objects     Private function __construct ()     {        echo ' I am constructed ';    }  & nbsp; //Singleton method     public static function singleton ()     {         if (!isset (self:: $instance)) {             $c = __class__;             self:: $instance = new $c;        }         return self:: $instance;   &nBsp }        //Example common methods in class     public function bark ()     {         echo ' woof! ';    }    /Prevent users from copying object instances     Public Function __clone ()     {& nbsp;       Trigger_error (' Clone is not allowed. ', e_user_error);    }}?>

So we can get a unique object of the example class.

<?php//This notation will be wrong, because the construction method is declared private $test = new Example; The following will get the singleton object of the Example class $test = Example::singleton (); $test->bark (); Copying an object will result in a e_user_error. $test _clone = Clone $test;?>

17.PHP 5 Adds a final keyword. If a method in the parent class is declared final, the subclass cannot overwrite the method, and if a class is declared final, it cannot be inherited.

18. Object replication can be done by using the Clone keyword (if the __clone () method exists in the object, it is called first). The __clone () method in the object cannot be called directly. $copy _of_object = Clone $object; When the object is copied, PHP5 performs a "shallow copy" of all properties of the object (shallow copy). The references in all the attributes remain unchanged, pointing to the original variable. If the __clone () method is defined, the __clone () method in the newly created object (copy generated object) is called and can be used to modify the value of the property, if necessary.

19. Object comparison when comparing two object variables using the contrast operator (= =), the principle of comparison is that if the properties and property values of two objects are equal, and two objects are instances of the same class, the two object variables are equal. If you use the strict equality operator (= = =), the two object variables must point to the same instance of a class (that is, the same object).

20. Objects and references to PHP are aliases, that is, two different variable names point to the same content. In PhP5, an object variable has no longer saved the value of the entire object. Just save an identifier to access the real object content. When an object is passed as a parameter, returned as a result, or assigned to another variable, the other variable is not a reference to the original, except that they all hold a copy of the same identifier that points to the true content of the same object

PHP Object-oriented basic knowledge points summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.