object-oriented Programming in PHP: Approaches to large PHP projects _php tips

Source: Internet
Author: User
Tags explode inheritance lowercase serialization
This article describes object-oriented programming (OOP) in PHP. I'll show you how to use object-oriented concepts to make fewer code but better programs. Good luck to all of you.

The concept of object-oriented programming has a different perspective for each author, and I remind you of what an object-oriented language should be:
-Data abstraction and information hiding

Ways to encapsulate a class in PHP:

Class Something {
In the OOP classes are usually named starting with a caps letter.
var $x;

function SetX ($v) {
Methods start in lowercase then with 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 good standard.

The data members of a class in PHP use the "var" definition, and the data members are not typed until they are assigned. A data member may be an integer, an array, a union array (associative array), or even an object. method to define a function in a class, to access data members in a method, you must use a $this->name method, otherwise it is a local variable for 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 object (instead of the Class) member variable in obj, and then GetX returns the value 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. You should use a member function to set the value of a member variable and to read a member variable by using a member function. If you think that member variables are not accessible, in addition to using member functions, you will become a good object-oriented programmer. Unfortunately, PHP itself has no way of declaring that a variable is private, so it allows bad code to exist.

Inheritance in PHP is declared using extend.

Class Another extends something {
var $y;
function Sety ($v) {
Methods start in lowercase then with lowercase to seperate
Words in the method name Example Getvalueofarea ()
$this->y= $v;

function GetY () {
return $this->y;

Such "Another" objects have the member variables and method functions of the parent class, plus their
member variables and member functions. Such as:

$obj 2=new Another;
$obj 2->setx (6);
$obj 2->sety (7);

Multiple inheritance is not supported, so you cannot allow a class to inherit multiple classes.

You can redefine the method in the inheriting class, and if we redefine the GetX in "Another", then we no longer have access to the member function GetX in "something". Similarly, if we declare a member variable with the same name as the parent class in the inheriting class, then the variable of the inheriting class hides the same variable of the parent class.

You can define the constructor of a class, which is a member function with the same name as the class, which is invoked when you create the object of the class.

Class Something {
var $x;

function something ($y) {
$this->x= $y;

function SetX ($v) {
$this->x= $v;

function GetX () {
return $this->x;

So you can create an object in the following ways:

$obj =new Something (6);

constructor automatically assigns a value of 5 to member variable x, constructors and member functions are normal PHP functions, so you can use the default arguments.

function something ($x = "3", $y = "5")

And 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 default parameters are defined in the same way as C + +, so you can't pass a value to Y but let X take the default, the argument passes from left to right, and when there are no more arguments, the function uses the default arguments.

Only when the constructor of the inheriting class is called, the object of the inheriting class is created, and the constructor of the parent class is not invoked, which is a feature of PHP's different object-oriented languages, because the constructor call chain is the characteristic of object-oriented programming. If you want to call the constructor of the base class, you have to call it explicitly in the constructor of the inheriting class. This makes it work because the methods of the parent class in the inheriting class are all available.

function Another () {
$this->something (); Explicit call to base class constructor.

A good mechanism in object-oriented programming is to use abstract classes, which are classes that cannot be instantiated but are used to define an interface for an inherited class. Designers often use abstract classes to force programmers to inherit only from a particular base class, so they can determine what functionality is required for a new class, but there is no standard way to do this in PHP, but:
If you are defining a base class that requires this feature, you can call "die" in the constructor, so you can make sure that it cannot be instantiated, now define the function of the abstract class and Invoke "die" in each function, if the programmer does not want to redefine the function of the base class directly in the inheriting class, an error will occur. In addition, you need to be sure that because PHP has no type, some objects are created from inheriting classes that inherit from the base class, so add a method to identify the class in the base class (return "some identities") and verify this when you receive an object as an argument. But for a rogue program, because he can redefine this function in an inherited class, it usually works only for lazy programmers. Of course, the best way is to prevent the program from contacting the base class code to provide only the interface.

Overloading is not supported in PHP. In object-oriented programming you can overload a member function of the same name by defining different types of parameters and how much. PHP is a loosely typed language, so parameter type overloading is useless, and the same number of parameters cannot be overloaded.

Sometimes it is useful to overload constructors in object-oriented programming, so you can create different objects in different ways (by passing different number of parameters). A small door can do this:

Class Myclass {
function Myclass () {
$name = "Myclass". Func_num_args ();
$this-> $name ();
$this-> $name () is usually wrong but
$name is a string with the name of the "

function Myclass1 ($x) {

function Myclass2 ($x, $y) {

This approach can partially achieve the purpose of overloading.

$obj 1=new Myclass (1); would call Myclass1
$obj 2=new Myclass (1,2); would call Myclass2

I feel good!


Polymorphism is defined as the ability of an object to invoke that method when an object is passed as a parameter at run time. For example, a class that defines the method "draw", inherits the class to redefine the behavior of the "draw" to draw a circle or a square, so that you have a function with a parameter of x that can be invoked in a function $x->draw (). If polymorphism is supported, the invocation of the "draw" method depends on the type of Object X. Polymorphism is naturally supported in PHP (think about this situation. If compiled in the C + + compiler, which method is invoked?) However, you do not know what type of object is, of course, this is not the case now. Fortunately, PHP supports polymorphism.

function nicedrawing ($x) {
Supose This is the class Board.
$x->draw ();

$obj =new Circle (3,187);
$obj 2=new Rectangle (4,5);

$board->nicedrawing ($obj); Would call the draw method of Circle.
$board->nicedrawing ($obj 2); Would call the draw method of Rectangle.

Object oriented Programming in PHP

Pure object-oriented people think that PHP is not a real object-oriented language, this is true. PHP is a hybrid language that you can use with object-oriented or traditional structural programming. For large projects, however, you might or need to use a purely object-oriented approach to define classes and use only objects and classes in your project. Increasingly large projects benefit from the use of object-oriented methods, which are easy to maintain, easy to understand and reuse. This is the basic of software engineering. Using these concepts in web design is the key to future success.

Advanced object-oriented Technology in PHP

After reviewing the basic object-oriented concepts, I'll introduce some of the more advanced techniques.


PHP does not support persistent objects, and persistent objects in object-oriented languages are objects that have been invoked many times by applications that still maintain their state and functionality, meaning that there is a way to save objects to a file or database and then reload the object. This mechanism is called serialization. PHP has a serialized function that can be invoked in an object, and the serialization function returns a String representing the object. The serialization function then holds the member data rather than the member function.

In PHP4, you can still call the object's method function if you serialize an object to a string $s, then delete the object, and then drag the row object to the $obj. But I do not recommend this approach because (a) This feature does not necessarily support in the future (b) This leads to an illusion if you save the serialized object to disk and exit the program. When you rerun this script in the future, you cannot drag this object and expect the object's method function to remain valid because the serialized string does not represent any member functions. Finally, serializing the member variables of the saved objects is useful in PHP, just so. (You can serialize the union array and arrays to disk).


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

... some months later

Load str from disk
$obj 2=unserialize ($STR)

In the example above, you can recover a member variable without a member function (according to the document). This leads to $obj 2->x is
The only way to access a member variable (because there is no member function).

There are a few ways to solve this problem, but I'll leave it to you because it will mess up this clean document.
I want PHP to fully support serialization in the future.

Using classes to manipulate saved data

A good place in PHP and object-oriented programming is that you can easily define a class to manipulate something and invoke the appropriate class when needed. If you have an HTML file, you need to select a product by selecting its ID number, and your data is stored in the database, and you want to display information about the product, such as price and so on. You have different kinds of products and the same actions have different meanings for different products. For example, displaying a sound means playing it, while for other products it is likely to display a picture stored in the database. You can use object-oriented programming and PHP to achieve less code but better.

Define a class, define the methods that the class should have, and then define the class (Sounditem class, Viewableitem class, etc.) of each product by inheritance, and redefine the methods of each product class so that they are as you want. Define a class for each product type based on the Product Type field of the table you saved in the database, and a typical product table should have fields (ID, type, price, description, etc.). In the script you get the type information from the table in the database, and then instantiate the object of the corresponding class:

$obj =new $type ();
$obj->action ();

This is a comparison of PHP features, you can call the $obj display method or other methods without going to the type of object. With this technique, when you add a new type of object, you don't need to modify the script. This method is a bit powerful, is to define the methods that all objects should have, regardless of their type, and then implement them in different ways in different classes, so that you can use them in scripts for different types of objects, no if, no two programmers in the same file, always happy. Do you believe programming is so happy? Low maintenance cost and reusable?

If you lead a group of programmers, the best approach is to divide the tasks, and each person can be responsible for a particular category and object. Internationalization can be solved with the same technology, so that the appropriate classes correspond to the different languages chosen by the user, and so on.

Replication and cloning

When you create an object $obj, you can use $obj 2 = $obj to copy an object, the new object is a copy of the $obj (not a reference), so the new object after the assignment has $obj the same new state. Sometimes you don't want to, just want to create the same new object as obj, call the constructor of the new object as if you had used the command. This can be achieved through the serialization of PHP and the use of base classes and other classes that must inherit from the base class.

In a dangerous zone.

When you serialize an object, you get a string that has a specific format, and if you are curious, you may find the secret, one of the things in the string is the name of the class, and you can undo 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 in "universe":

Class Universe {
function __clone () {
$herring =serialize ($this);
$vec =explode (":", $herring);
$nam =str_replace ("\" "," ", $vec [2]);
$ret = new $nam;
return $ret;


$obj =new something ();
Something Extends Universe!!
$other = $obj->__clone ();

What you get is the new object of class something like using new, and constructors are called and so on. I don't know if it's useful to you, it's a good practice, Universe class knows the name of its inheriting class. For you, the only limit is your imagination!!!

Note: I am using PHP4, and there are some things in the article that may not be suitable for PHP3.


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.