Object-oriented programming in PHP: Solutions to large-scale PHP engineering-PHP Tutorial

Source: Internet
Author: User
Object-oriented programming in PHP: a method for connecting to a large PHP project. This article introduces object-oriented programming (OOP) in PHP ). I will demonstrate how to use object-oriented concepts to compile less code but better programs. Good luck. This article introduces object-oriented programming (OOP) in PHP ). I will demonstrate how to use object-oriented concepts to compile less code but better programs. Good luck.

The concept of object-oriented programming has different views for each author. I would like to remind you of the following:
-Data abstraction and information hiding
-Inheritance
-Polymorphism

How to encapsulate classes in PHP:

Class Something {
// In OOP classes are usually named starting with a cap letter.
Var $ x;

Function setX ($ v ){
// Methods start in lowercase then use lowercase to seprate
// Words in the method name example getValueOfArea ()
$ This-> x = $ v;
}

Function getX (){
Return $ this-> x;
}
}
?>

Of course you can use your own method, but there is always a standard.

The data member of the class in PHP is defined by "var". The data member is of no type until it is assigned a value. A data member may be an integer, array, associative array, or even an object ). A method is defined as a function in a class. to access data members in a method, you must use $ this-> name. Otherwise, a method is a local variable of a function.

Use new to create an object

$ Obj = new Something;

Then use the member function

$ Obj-> setX (5 );
$ See = $ obj-> getX ();

The setX member function assigns 5 to the member variables in the object (rather than the class) obj, and then returns the value of getX 5.

You can also use object references to access member variables, such as $ obj-> x = 6. However, this is not a good object-oriented programming method. I insist that you should use the member function to set the value of the member variable and read the member variable through the member function. If you think that member variables are unaccessable, in addition to using member functions, you will become a good object-oriented programmer. Unfortunately, PHP itself cannot declare that a variable is private, so bad code is allowed.

In PHP, extend is used for inheritance.


Class Another extends Something {
Var $ y;
Function setY ($ v ){
// Methods start in lowercase then use lowercase to seperate
// Words in the method name example getValueOfArea ()
$ This-> y = $ v;
}

Function getY (){
Return $ this-> y;
}
}
?>

In this way, the object of the "Another" class has the member variables and method functions used by the parent class, plus
Member variables and member functions. For example:

$ Obj2 = new Another;
$ Obj2-> setX (6 );
$ Obj2-> setY (7 );

Multi-inheritance is not supported, so you cannot let a class inherit multiple classes.

You can redefine the method in the inheritance class. if we redefine getX in "Another", we will no longer be able to access the member function getX in "Something. similarly, if we declare a member variable with the same name as the parent class in the inherited class, the variable that inherits the class will hide the variable with the same name as the parent class.

You can define a class constructor. The constructor is a member function with the same name as the class and is called when you create class objects.


Class Something {
Var $ x;

Function Something ($ y ){
$ This-> x = $ y;
}

Function setX ($ v ){
$ This-> x = $ v;
}

Function getX (){
Return $ this-> x;
}
}
?>

You can use the following method to create an object:

$ Obj = new Something (6 );

The constructor automatically assigns 5 values to the member variable x. The constructor and member functions are common PHP functions, so you can use the default parameters.

Function Something ($ x = "3", $ y = "5 ")

Then:

$ Obj = new Something (); // x = 3 and y = 5
$ Obj = new Something (8); // x = 8 and y = 5
$ Obj = new Something (8, 9); // x = 8 and y = 9

The definition method of the default parameter is the same as that of C ++. Therefore, you cannot pass a value to Y but let X take the default value. The real parameter is passed from left to right, if no more arguments are available, the function uses the default parameters.

Only when the constructor of the inherited class is called Can the object of the inherited class be created, and the constructor of the parent class is not called. this is a feature of different PHP object-oriented languages, because the constructor call chain is a feature of object-oriented programming. If you want to call the base class constructor, you have to explicitly call it in the constructor of the inherited class. This method works because all methods of the parent class are available in the inherited class.

Function Another (){
$ This-> y = 5;
$ This-> Something (); // explicit call to base class constructor.
}
?>

In object-oriented programming, a good mechanism is to use abstract classes. abstract classes are classes that cannot be instantiated but are used to define interfaces for inherited classes. Designers often use abstract classes to force programmers to inherit only from a specific base class, so they can determine that the new class has the required functions, but there is no standard way to do this in PHP, however:
If you need this feature to define the base class, you can call "die" in the constructor to ensure that it cannot be instantiated, now define the abstract class function and call "die" in each function. if the programmer in the inherited class directly calls the base class function without redefinition, an error will be generated. In addition, you need to be sure that because PHP has no type, some objects are created from the inheritance class inherited from the base class, therefore, add a method in the base class to identify the class (return "some identifiers") and verify this, when you receive an object as a parameter. But it is useless for a villain program, because he can redefine this function in the inheritance class, usually this method only works for the lazy programmer. Of course, the best way is to prevent the program from accessing the code of the base class and only provide the interface.

Overload is not supported in PHP. In object-oriented programming, you can reload a member function with the same name by defining different parameter types and quantity. PHP is a loose type language, so it is useless to reload the parameter type, and the same number of parameters cannot be reloaded.

Sometimes, overload constructors are useful in object-oriented programming, so you can create different objects in different ways (by passing different parameter numbers ). A clever man can do this:

Class Myclass {
Function Myclass (){
$ Name = "Myclass". func_num_args ();
$ This-> $ name ();
// Note that $ this-> $ name () is usually wrong but here
// $ Name is a string with the name of the method to call.
}

Function Myclass1 ($ x ){
Code;
}

Function Myclass2 ($ x, $ y ){
Code;
}
}
?>

This method can partially achieve the purpose of overloading.

$ Obj1 = new Myclass (1); // Will call Myclass1
$ Obj2 = new Myclass (1, 2); // Will call Myclass2

Not bad!

Polymorphism

Polymorphism is defined as the ability of an object to call a method when it is passed as a parameter at runtime. For example, if you use a class to define the method "draw" and inherit the class to redefine the behavior of "draw" to draw circles or squares, then you have a function with the parameter x, you can call $ x-> draw () in the function (). if polymorphism is supported, the call to the "draw" method depends on the type of object x. Polymorphism is naturally supported in PHP (think about this situation in the C ++ compiler if it is compiled, that method is called? However, you don't know what the object type is. Of course this is not the case now ). Fortunately, PHP supports polymorphism.

Function niceDrawing ($ x ){
// Supose this is a method of the class Board.
$ X-> draw ();
}

$ Obj = new Circle (3,187 );
$ Obj2 = new Rectangle (4, 5 );

$ Board-> niceDrawing ($ obj); // will call the draw method of Circle.
$ Board-> niceDrawing ($ obj2); // will call the draw method of Rectangle.
?>

PHP object-oriented programming

It is true that PHP is not a real object-oriented language. PHP is a hybrid language that you can use in object-oriented or traditional structured programming methods. For large projects, however, you may or need to use a pure object-oriented method to define classes and use only objects and classes in your project. More and more large projects will benefit from the use of object-oriented methods. object-oriented projects are very easy to maintain, easy to understand and reuse. This is the basis of software engineering. Using these concepts is the key to future success in website design.

Advanced object-oriented technology in PHP

After reviewing the basic concepts of object-oriented, I will introduce some more advanced technologies.

Serializing

PHP does not support persistent objects. in object-oriented languages, persistent objects are some objects that remain in the state and function after multiple calls by applications, this means that an object can be saved to a file or database and then reloaded. This mechanism is called serialization. PHP has a serialization function that can be called in an object. the serialization function returns a string representing this object. The serialized function then stores the member data rather than the member function.

In PHP4, if you serialize an object to the string $ s, delete the object, and deserialize the object to $ obj, you can still call the method function of the object. But I do not recommend this method, because (a) This feature will not necessarily support (B) in the future, which leads to an illusion if you save the serialized object to the disk and exit the program. When you re-run the script in the future, you cannot deserialize the object and expect that the method function of the object will still be valid, because the serialized string does not represent any member function. Finally, serialized member variables for saving objects are very useful in PHP (you can concatenate arrays and arrays into the disk ).

Example:

$ Obj = new Classfoo ();
$ Str = serialize ($ obj );
// Save $ str to disk

//... Some months later

// Load str from disk
$ Obj2 = unserialize ($ str)
?>

In the above example, you can restore member variables without member functions (according to the document ). This causes $ obj2-> x to be
The only way to access member variables (because there is no member function ).

There are still some ways to solve this problem, but I will leave it for you because it will Dirty this clean document.
I hope PHP will support serialization in the future.

Use classes to manipulate stored data

A better part of PHP and object-oriented programming is that you can easily define classes to manipulate something and call appropriate classes when needed. Suppose there is an HTML file. you need to select a product by selecting the product ID. your data is stored in the database, and you want to display the product information, such as the price. You have different types of products, and the same action has different meanings for different products. For example, displaying a sound means playing it, while other products may be displaying an image stored in the database. You can use object-oriented programming and PHP, with fewer but better code.

Define a class, define the methods that the class should have, then define the classes of each product (SoundItem class, ViewableItem class, etc.) through inheritance, and redefine the methods of each product class, make them as needed. Define a class for each product type based on the product type field of the table you saved in the database. a typical product table should have fields (id, type, price, description, and so on ). In the script, you obtain the type information from the database table and instantiate the object of the corresponding class:

$ Obj = new $ type ();
$ Obj-> action ();
?>

This is a comparative feature of PHP. you can call the $ obj display method or other methods without worrying about the object type. With this technology, when you add a new type of object, you do not need to modify the script. This method is a bit powerful, that is, to define all the methods that an object should have regardless of its type, and then implement them in different ways in different classes, in this way, they can be used for different types of objects in the script, and there is no if. no two programmers are always happy in the same file. Do you believe that programming is so happy? Small maintenance cost and reusable?

If you lead a group of programmers, the best way is to divide tasks. each person can be responsible for a certain type and object. Internationalization can be solved using the same technology, so that appropriate classes correspond to different languages selected by users.

Copy and clone

When you create an object $ obj, you can use $ obj2 = $ obj to copy an object. The new object is a copy of $ obj (not a reference ), therefore, $ obj is in the same state as the new object after the assignment. Sometimes you don't want to do this. you just want to create a new object like obj, and call the constructor of the new object as if you used the new command. This can be achieved through the serialization of PHP and the use of base classes, and other classes must be inherited from the base class.


Dangerous zones

When you serialize an object, you get a string with a specific format. if you are curious, you may find the secret. one thing in the string is the name of the class, you can unlock it:

$ Herring = serialize ($ obj );
$ Vec = explode (":", $ herring );
$ Nam = str_replace ("\" "," ", $ vec [2]);
?>

Suppose you create a class "Universe" and make all classes inherit from "Universe", you can define a clone method in "Universe:

Class Universe {
Function _ clone (){
$ Herring = serialize ($ this );
$ Vec = explode (":", $ herring );
$ Nam = str_replace ("\" "," ", $ vec [2]);
$ Ret = new $ nam;
Return $ ret;
}
}

// Then:

$ Obj = new Something ();
// Something extends Universe !!
$ Other = $ obj->__ clone ();
?>

What you get is a new object like Something, and the constructor is called. I don't know if this is useful to you. this is a good practice. The Universe class knows the name of its inherited class. The only limit for you is your imagination !!!

Note: I use PHP4, and some of the articles may not be suitable for PHP3.

-End-

Compile (OOP ). I will demonstrate how to use object-oriented concepts to compile less code but better programs. Good luck. Overview of object-oriented programming...

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.