Full knowledge of PHP classes and objects

Source: Internet
Author: User
Tags autoload

Directory

Full parsing of PHP classes and objects (i)

Full parsing of PHP classes and objects (ii)

Full parsing of PHP classes and objects (iii)

1. Classes and objects

Object: An individual that actually exists in each of the objects in the class. $a =new User (); $ A after instantiation
Reference: PHP aliases, two different variable names pointing to the same content

Encapsulation: Organizing the properties and methods of an object in a class (logical unit)
Inheritance: The purpose of code reuse is to create a new class based on the original class;
Polymorphic: A pointer to the parent class type is allowed to assign a pointer to the child class type.
-------------------------------------

2. Automatically load objects:

Automatic loading by defining special autoload functions, this function is called automatically when references to classes that are not defined in the script are invoked.

[PHP] View plaincopyprint? function AutoLoad ($class) {   require_once ("classes/$class. class.php");}

Why to use AutoLoad

1, first of all do not know where this class of files are stored,
2, the other one is not know when to use this file.
3, especially when the project file is very long, it is impossible to write the require in the beginning section of each file.

Instead of a
Require_once ("classes/books.class.php");
Require_once ("classes/employees.class.php");
Require_once ("classes/events.class.php");
Require_once ("classes/patrons.class.php");

Zend recommends one of the most popular ways to include a path in the file name. For example, the following example:

[PHP] View plaincopyprint?    View Sourceprint?      Main.class              function AutoLoad ($class _name) {              $path = Str_replace (' _ ', Directory_separator, $class _name);              Require_once $path. " php ';          }

temp = new Main_super_class ();

All underscores are replaced with delimiters in the path, and the main/super/class.php file is removed from the previous example.

Disadvantages:

In the coding process, it is important to know exactly where the code file should be located,

And because the file path is hard-coded in the class name, if you need to modify the structure of the folder, we must manually modify all the class names.

Using the ' Include all ' method is convenient if you are in a development environment and are not very concerned about speed.
By placing all the class files in one or several specific folders, and then looking through the load.
For example

   <?php               $arr = Array (              ' project/classes ',             ' Project/classes/children ',             ' project/interfaces '         ) ;               foreach ($arr as $dir) {                   $dir _list = Opendir ($dir);                  while ($file = Readdir ($dir _list)) {                  $path = $dir. Directory_separator. $file;                  if (In_array ($file, Array ('. ', '. ')) | | Is_dir ($PATH))                      continue;                 if (Strpos ($file, ". class.php"))                      require_once $path;              }         }                ? >

Another method is to create an associated configuration file between the class file and his location, for example:

    View Sourceprint?      configuration.php               array_of_associations = Array (             ' mainsuperclass ' = ' c:/main/super/class.php ',             ' Mainpoorclass ' = ' c:/blablabla/gy.php '         );

The called file

    <?php             require ' autoload_generated.php ';            function AutoLoad ($className) {                global $autoload _list;                Require_once $autoload _list[$className];             }              $x = new A ();         ? >

------------------------------------------------

3. Constructors and destructors

The PHP construction method construct () allows the constructor to be executed before instantiating a class.

The constructor method is a special method in the class. When you use the new operator to create an instance of a class, the constructor method is automatically called, and its name must be construct ().

(Only one construction method can be declared in a class, but the constructor is called once every time the object is created, and the method cannot be invoked actively.
Therefore, it is often used to perform some useful initialization tasks. The method has no return value. )

Function: Initializes an object when it is used to create an object
The subclass performs the classification of the constructor Parent::construct ().

destructor: Destruct () Definition: Special inner member function, no return type, no parameters, no arbitrary invocation, no overloading;
The resource allocated in the constructor is released automatically by the system when the class object is at the end of its life.

And the constructor method corresponds to the Destructor method, the destructor allows some operations to be performed before destroying a class or to perform some functions, such as closing a file, releasing a result set, and so on.
Destructors cannot have any arguments, and their names must be destruct ().
Role: Cleans up the aftermath, for example, using new to open up a memory space when creating an object, use a destructor to release the resources allocated in the constructor before exiting.

Example:

    Class Person {public          $name;          public $age;                Defines a constructor method that initializes the assignment public          function construct ($name, $age) {              $this->name= $name;              $this->age= $age;          }          Public function Say () {              echo ' My name is: '. $this->name. ' <br/> ";              echo "My Age is:". $this->age;          }          destructor function          destruct ()          {              echo "goodbye:". $this->name;          }      }            $p 1=new person ("Ren", +);      $p 1->say ();

---------------------------------------------------------------

4. Access control

Access control to a property or method is achieved by adding the keyword public, protected, or private earlier.
A class member defined by public can be accessed from anywhere;
A class member defined by protected can be accessed by the subclass and parent of the class in which it resides (and, of course, the class where the member resides);
Private-defined class members can only be accessed by their own class.
Access control for class members
Class members must be defined using the keyword public, protected, or private

Access control of the method
Methods in a class must be defined using the keyword public, protected, or private. If these keywords are not set, the method is set to the default public.

Example:

Class MyClass  {public      $public = ' public ';      Protected $protected = ' protected ';      Private $private = ' private ';        function Printhello ()      {          echo $this->public;          echo $this->protected;          echo $this->private;      }  }    $obj = new MyClass ();  Echo $obj->public; This line can be performed normally  echo $obj->protected;//This guild produces a fatal error  echo $obj->private;//This line can also produce a fatal error  $obj Printhello (); Output public, Protected, and Private

-------------------------------------------------------------

5. Object inheritance

Inheritance definition: The purpose of code reuse is to create a new class based on the original class;
--------------------------------------
Overwrite is used for object inheritance
Overloading is a method with different parameters of the same method name in a single object
--------------------------------------

Inheritance has been well-known for a programming feature, and the PHP object model also uses inheritance. Inheritance will affect the relationship between classes and classes, objects and objects.

For example, 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.

Inheritance is very useful for the design and abstraction of features, and adding new functionality to similar objects eliminates the need to re-write these common features.

    Class Person {public          $name;          public $age;                function say () {              echo "My name is:". $this->name. " <br/> ";          echo "My Age is:". $this->age;          }      }            Classes inherit class      Student extends person {          var $school;    Student's School attribute                    function study () {              echo "My name is:". $this->name. " <br/> ";              echo "My shool is:". $this->school;          }             }            $t 1 = new Student ();      $t 1->name = "Zhangsan";      $t 1->school = "Beijindaxue";      $t 1->study ();

------- --------- ------ --------- -------- -----

6. Scope resolution operator (::)

The scope resolution operator (also known as Paamayim Nekudotayim) or, more simply, a pair of colons, can be used to access static members, methods, and constants, and can also be used to override members and methods in a class.
When you access these static members, methods, and constants outside of the 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.
Attention:
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

Example:

    <?php      class Otherclass extends MyClass      {public          static $my _static = ' static var ';                public static function Doublecolon () {              echo parent::const_value. "\ n";              echo Self:: $my _static. "\ n";          }      }            Otherclass::d Oublecolon ();      ? >
Related Article

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.