How to develop a large PHP project _php tutorial

Source: Internet
Author: User
How to develop a large PHP project here is a description of object-oriented programming in PHP (Oop,object oriented programming). will show you how to reduce coding and improve quality by using some of the concepts of OOP and PHP techniques. Good luck!

The concept of object-oriented programming:
Different authors may disagree, but an OOP language must have the following:

Abstract data types and information encapsulation
Inherited
Polymorphic

In PHP, the encapsulation is done through a class:

Code:

Class Something {
In an OOP class, the first character is usually capitalized
var $x;
function SetX ($v) {
Method starts with a lowercase word, and then uses uppercase letters to separate words, such as Getvalueofarea ()
$this->x= $v;
}
function GetX () {
return $this->x;
}
}
?>



Of course you can define your own preferences, but it's better to keep a standard, which is more effective.

Data members are defined in a class using the "var" declaration, which is not typed until the data member is assigned a value. A data member can be an integer, an array, an associated array (associative array), or an object.

method is defined as a function in a class, you should use $this->name when accessing a class member variable in a method, otherwise it can only be a local variable for a method.

Use the new operator to create an object:

$obj =new Something;

You can then use the member function to pass:

$obj->setx (5);
$see = $obj->getx ();

In this example, the SETX member function assigns 5 to the object's member variable x (not the Class), and then Getx returns its value 5.

You can access data members as $obj->x=6, which is not a good oop habit. I strongly recommend accessing member variables through methods. If you consider the member variable to be non-processing and use the method only through the object handle, you will be a good OOP programmer. Unfortunately, PHP does not support declaring private member variables, so bad code is also allowed in PHP.

Inheritance is easy to implement in PHP, as long as the Extend keyword is used.

Code:

Class Another extends Something {
var $y;
function Sety ($v) {
$this->y= $v;
}
function GetY () {
return $this->y;
}
}
?>



Objects of the "another" class now have all the data members and methods of the parent class (Something), plus their own data members and methods.

You can use

Code:

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



PHP does not now support multiple inheritance, so you cannot derive new classes from two or more of the two classes.

You can redefine a method in a derived class, and if we redefine the Getx method in the "Another" class, we cannot use the Getx method in "Something". If you declare a data member in a derived class that has the same name as implementation, it will "hide" the data members of the base class when you process it.

You can define constructors in your class. A constructor is a method that has the same name as a class, and is called when you create an object of a class, for example:

Code:

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 by:

$obj =new Something (6);

The constructor automatically assigns a value of 6 to the data variable, x. Constructors and methods are normal 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 default parameter uses C + +, so you can't ignore the value of Y, and give X a default parameter, which is assigned from left to right, and if the passed parameter is less than the required parameter, the default parameter is used.

When an object of a derived class is created, only its constructor is called, the constructor of the parent class is not called, and if you want to call the constructor of the base class, you must display the call in the constructor of the derived class. You can do this because the methods of all the parent classes in the derived class are available.

Code:

function another () {
$this->y=5;
$this->something ();
Show call base class constructor
}
?>



A good mechanism for OOP is to use abstract classes. Abstract classes are not instantiated and can only be supplied to a derived class interface. Designers often use abstract classes to force programmers to derive from base classes, which ensures that new classes contain some expected functionality. There are no standard methods in PHP, but:

If you need this feature, you can define the base class and add a "die" call after its constructor, so that the base class is not instantiated, and now add a "die" statement behind each method (interface), so if a programmer does not overwrite the method in the derived class, an error will be thrown. And because PHP is untyped, you might want to make sure that an object is derived from your base class, then add a method in the base class to the identity of the literal class (returning an Identity ID), and verify the value when you receive an object parameter. Of course, if an evil, bad programmer overrides this method in a derived class, this method does not work, but the general problem is that it is more of a lazy programmer than an evil one.

Of course, it's good for the base class to be impossible for programmers to see, as long as the interface is printed out to do their job.

There are no destructors in PHP.

Overloads (unlike overrides) are not supported in PHP. In OOP, you can overload a method to implement two or more methods with the same name, but with different numbers or types of arguments (this depends on the language). PHP is a loosely typed language, so it does not work with type overloading, but overloading with different number of parameters does not work.

Sometimes overloading constructors in OOP is great, so you can create objects in different ways (passing different numbers of parameters). in PHP
The techniques for implementing it are:

Code:

Class Myclass {
function Myclass () {
$name = "Myclass". Func_num_args ();
$this $name ();
Note that $this->name () is generally wrong, but here $name is the name of the method that will be called
}
function Myclass1 ($x) {
Code
}
function Myclass2 ($x, $y) {
Code
}
}
?>



By additional processing in the class, using this class is transparent to the user:

$obj 1=new Myclass (' 1 '); Will call Myclass1

$obj 2=new Myclass (' 1 ', ' 2 '); Will call Myclass2

Sometimes this is very useful.

Polymorphic
Polymorphism is the ability of an object to determine the method of which object to invoke, depending on the passed object parameters at run time. For example, if you have a figure class, it defines a draw method. and derive the circle and rectangle classes, in which you override the Draw method, you may also have a function that expects to use a parameter x, and can call $x->draw (). If you have polymorphism, calling which draw method depends on the type of object you pass to the function.

Polymorphism in an interpreted language like PHP (imagine a C + + compiler generating such code, which method should you call?) You also don't know what type of object you have, well, it's not the point, it's very easy and natural. So PHP certainly supports polymorphism.

Code:

function nicedrawing ($x) {
Suppose this is a method of the Board class
$x->draw ();
}
$obj =new Circle (3,187);
$obj 2=new Rectangle (4,5);
$board->nicedrawing ($obj);
The draw method that will call circle
$board->nicedrawing ($obj 2);
The draw method that will call rectangle
?>



Object-oriented Programming with PHP
Some "purists" (purists) may say that PHP is not a true object-oriented language, which is true. PHP is a mixed language, you can use OOP, or you can use traditional procedural programming. However, for large projects, you might want to use pure OOP in PHP to declare classes, and only use objects and classes in your project.

As projects grow larger, using OOP can be helpful, and OOP code is easy to maintain, easy to understand and reuse. These are software engineering.
The basis. Applying these concepts to Web-based projects is the key to future site success.

Advanced OOP Technology for PHP
After reading the basic OOP concepts, I can show you more advanced techniques:

Serialization (serializing)
While PHP does not support persistent objects, permanent objects in OOP are objects that can hold state and functionality in references to multiple apps, which means having the ability to save objects to a file or database, and to load objects later. This is called the serialization mechanism. PHP has a serialization method that can be called through an object, and the serialization method can return a string representation of an object. However, serialization saves only the member data of the object and does not package the session method.

In PHP4, if you serialize an object into a string $s and then release the object, and then deserialize the object to $obj, you can continue to use the object's Method! I do not recommend this because (a) there is no guarantee in the documentation that this behavior will still be available in later versions. (b) This may lead to a misunderstanding when you save a serialized version to disk and exit the script. When you run the script later, you cannot expect the object's methods to be there when deserializing an object, because the string representation does not include the method at all.

In summary, PHP serialization is useful for saving member variables of an object. (You can also serialize related arrays and arrays into a file).

Example:

Code:

$obj =new Classfoo ();
$str =serialize ($obj);
A few months later
Mount Str from disk
$obj 2=unserialize ($STR)
?>



You restored the member data, but did not include the method (according to the document). This leads to access to member variables only by similar use of $obj2->x (you have no other way!). The only way, so don't try it at home.

There are some ways to solve this problem, I keep it, because they are too bad for this concise article.

Using classes for data storage
A great thing about PHP and OOP is that you can easily define a class to manipulate something, and you can invoke the appropriate class whenever you want to use it. Suppose you have an HTML form that allows users to select a product by selecting the Product ID number. In the database has the product information, you want to display the product, show its price and so on. You have different types of products, and the same action may have different meanings for different products. For example, displaying a sound might mean playing it, but for other kinds of products it might mean displaying a picture in the database. You can use OOP or PHP to reduce coding and improve quality:

Define a product's class, define the method it should have (for example: Display), and then define the classes for each type of product, from the product class to come out (Sounditem class, Viewableitem class, etc.), covering the methods in the product class so that they act as you think.

A typical product table may have (ID, type, price, description, and so on), depending on the type of each product in the database, given the class name. Then in the processing script, you can remove the type value from the database and instantiate an object named type:


Code:

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



This is a very good feature of PHP, you can not consider the type of object, call $obj display method or other methods. With this technique, you don't need to modify the script to add a new type of object, just add a class that handles it.

This is a powerful feature, as long as you define the method without considering the types of all the objects, implement them in different ways, and then use them in the main script for any object, no if...else, no two programmers, only happy.

Now do you agree that programming is easy, maintenance is cheap, reusable is true?

If you manage a group of programmers, assigning jobs is easy, and everyone can be responsible for one type of object and the class that handles it.

Internationalization can be achieved through this technology, according to the user's chosen language field to apply the corresponding class can be, and so on.


Copy and Clone
When you create a $obj object, you can copy the object through the $obj2= $obj, and the new object is a copy of the $obj (not a reference), so it has a $obj state at that time. Sometimes, you don't want to, you just want to create a new object like the Obj class, you can call the class's constructor by using the new statement. It can also be implemented in PHP by serialization, and a base class, but all other classes are derived from the base class.


Enter hazardous areas
When you serialize an object, you get a string of some format, and if you're interested, you can tune it, where the string has the name of the class (too good!). ), you can take it out, like this:

Code:

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



So suppose you create a "Universe" class and force all classes to be extended from Universe, you can define a clone method in Universe, as follows:

Code:

Class Universe {
function Clone () {
$herring =serialize ($this);
$vec =explode (': ', $herring);
$nam =str_replace ("\" "," ', $vec [2]);
$ret =new $nam;
return $ret;
}
}
And then
$obj =new Something ();
Extending from Universe
$other = $obj->clone ();
?>



What you get is a new object of the Something class, which is the same as using the new method, which calls the constructor to create the object. I don't know if this is useful for you, but the Universe class can know the name of the derived class as a good experience. Imagination is the only limit. (Source: Wind Flash)

http://www.bkjia.com/PHPjc/314509.html www.bkjia.com true http://www.bkjia.com/PHPjc/314509.html techarticle How to develop a large PHP project here is a description of object-oriented programming in PHP (Oop,object oriented programming). will show you how to use some of the OOP concepts and PHP tips to ...

  • 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.