Full parsing of PHP classes and objects (i)

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.

1 [php] View plaincopyprint? 2 function __autoload ($class) {  3   require_once("classes/$ Class. class.php ");   4 }  

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:

1[PHP] View plaincopyprint?2 3View Sourceprint?4     //Main.class5       6     function__autoload ($class _name) {     7          $path=Str_replace(' _ ', Directory_separator,$class _name); 8          require_once $path.‘. Php; 9}

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 (' 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:

    classPerson { Public $name;  Public $age; //define a constructor method to initialize the assignment         Public function__construct ($name,$age) {              $this->name=$name; $this->age=$age; }           Public functionsay () {Echo"My name is:".$this->name. " <br/> "; Echo"My Age is:".$this-Age ; }          // Destructors        function__destruct () {Echo"Goodbye:".$this-name; }      }            $p 1=NewPerson ("Ren", 25); $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:

classMyClass { Public $public= ' Public '; protected $protected= ' Protected '; Private $private= ' Private '; functionPrinthello () {Echo $this- Public; Echo $this-protected; Echo $this-Private; }  }    $obj=NewMyClass (); Echo $obj- Public;//This line can be executed normally.Echo $obj-protected;//This guild produces a fatal error .Echo $obj-Private;//This line will 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.

    classPerson { Public $name;  Public $age; functionsay () {Echo"My name is:".$this->name. " <br/> "; Echo"My Age is:".$this-Age ; }      }            //Inheritance of Classes    classStudentextendsPerson {var $school;//the properties of the school where students are located                  functionStudy () {Echo"My name is:".$this->name. " <br/> "; Echo"My shool is:".$this-School; }             }            $t 1=NewStudent (); $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 ' 

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

Full parsing of PHP classes and objects (i)

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.