Object-oriented programming in PHP: Measures to large PHP projects

xiaoxiao2021-03-06  42

Object-oriented programming in PHP: Measures to large PHP projects

============================================================================================================================================================================================================= ==================

Original: Luis Argerich Translation: Allen Lee

This article describes the object-oriented programming (OOP) of PHP. I will demonstrate how to use object-oriented concepts

Compare less code but better programs. I wish you all good luck.

The concept of object-oriented programming has different views on every author, I will remind one of them

Object language should have anything:

Data Abstraction and Information Hide

- inheritance

- Polymorphism

Use the class in PHP to encapsulate:

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 normal name esample getValueofAREA ()

$ this-> x = $ V;

}

Function getX () {

Return $ THIS-> X;

}

}

?>

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

- Page 1 -

Data members in PHP use "VAR" definition, and the data member is not type until it is assigned. One

Data members may be an integer, array, a joint array (Associative Array) or even

Object. Method defines a function in the class, access data members in the method, you must use

$ this-> Name This method, otherwise it is a partial variable for a function.

Use new to create an object

$ Obj = new something;

Then use member functions

$ obj-> setX (5);

$ see = $ obj-> getx ();

The SETX member function will 5 assign a member variable in the object (instead of class) Obj, then getx

Return value 5.

You can also use object reference to access member variables, for example: $ 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 member variable.

Values ​​and through member functions to read member variables. If you think member variables are unbearable

Using Member Functions, you will become a good object-oriented programmer. But unfortunately

PHP itself has no way to state that a variable is private, so the bad code is allowed.

Inherit the use of Extend to declare in PHP.

Class Another Extends Something {

Var $ y;

Function SetY ($ V) {

// Methods Start in Lowercase Then Use Lowercase to SEPERATE

// Words in the normal name esample getValueofAREA ()

$ this-> y = $ v;}

Function game () {

Return $ this-> y;

}

}

?>

- Page 2 -

Such objects such as "Another" have the membership variables and method functions of the parent class, plus themselves

Member variables and member functions. Such as:

$ Obj2 = new another;

$ OBJ2-> SetX (6);

$ OBJ2-> Sety (7);

Multiple inheritance is not supported, so you can't let a class inherit multiple classes.

In the inheritance class, you can redefine the method if we redefine Getx in "Another".

Then we can no longer access the member function getx in "Something". Similarly, if we inherit

The class declare a member variable with the same name as the parent class, then the inherited variable will hide the same name variable of the parent class.

You can define a class constructor, constructor is the member function of the same name, in your creation

The object is called.

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 with the following method:

$ Obj = new Something (6);

The constructor automatic assignment 5 gives the member variable x, constructor, and member functions are ordinary 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 thing (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 C , so you can't pass a value to Y but let X default value.

The transmission of the arguments is from left to right, and the function will use the default parameter when there is no more real parameters.

- Page 3 -

Only when the inherited structure is called, the inherited object is created, and the constructor of the parent class is not

There is called, this is the characteristics of PHP different other object-oriented languages, because the constructor call chain is facing

Object programming features. If you want to call the constructor of the base class, you have to inherited the constructor of the class.

Call it in a flashlight. This work is because the method of the parent class in the inheritance class is available.

Function another () {

$ THIS-> Y = 5;

$ this-> Something (); // Explicit Call to base Class Construction.

}

?>

A good mechanism in object-oriented programming is the use of abstract classes, abstract classes are a kind of unmectable but

Used to define the interface of the inheritance class. Designers often use abstract classes to force programmers to only

The base class to inherit, so it can determine the function of new classes, but there is no standard approach in PHP.

Do this, but:

If you need this feature in defining the base class, you can call "Die" in the constructor so you

You can make sure it does not instantiate, now define the function of the abstract class and call "Die" in each function.

If the programmer does not want to redefine in the inheritance class, an error will be generated directly.

In addition, you need to be sure that because php is not type, some objects are created from the inheritance class from the base class, thus adding a method to identify classes in the base class (return "some identity") and verify this, when you

Received an object as a parameter. But it is useless for a villager program because he can

Deconsive this function in inheritance class, usually this method is only for lazy programmers. Of course, the best

The way is to prevent the program from contacting the base class only to provide an interface.

- Page 4 -

Heavy load is not supported in PHP. You can define different parameters and how much in object-oriented programming

To overload a member function of the same name. PHP is a loose type language, so the parameter type overload is

It is not used, and the number of different parameters is different.

Sometimes, the overloading constructor is useful in object-oriented programming, so you can create different ways.

Different objects (by passing different parameters). A small door 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 approach can be partially reached for the purpose of overload.

$ obj1 = new myclass (1); // Will Call myclass1

$ obj2 = new myclass (1, 2); // Will Call MyClass2

feel good!

- Page 5 -

Polymorphism

The polymorphism is defined as a parameter as a parameter when an object is passed, and the object can determine the call.

The ability of the method. For example, use a class to define how to "DRAW", inherited "DRAW"

Behavior draws circles or squares so you have a function of a parameter X. You can call in the function.

$ x-> draw (). If you support polymorphism, the call of the "DRAW" method depends on the object X

Types of. Multi-state is naturally supported in PHP (thinking about this situation if compiled in the C compiler,

That way is called? However, you don't know what the type of object is, of course, not this situation).

Fortunately, PHP supports polymorphism.

Function nicedrawing ($ x) {

// supose this is a mathod 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.

?>

Object-oriented programming of PHP

Pure objects believe that PHP is not a true object-oriented language, which is right. PHP is a mixed language,

You can use it with object or traditional structural programming methods. For large projects, however you can

Can or need to use pure object-oriented methods to define classes and use only objects and classes in your project. More

The larger projects are benefited from the use of object-oriented methods, and object-oriented projects are very easy to maintain, easy to understand and reuse. This is the basics of software engineering. Use these concepts in the website design

the key to success.

- Page 6 -

Advanced object-oriented technology in PHP

After reviewing the object-oriented basic concept, I will introduce some more advanced technology.

Serialization

PHP does not support persistence objects, in the object-oriented language, persistent objects are some applications multiple times

The call still maintains its status and function, which means there is a saving object to a file or database.

The object is then reloaded. This mechanism is called serialization. PHP has a serialization function, you can

The object is called, and the serialization function returns a string representing this object. The serialization function is then saved

It is a member data instead of a member function.

In PHP4, if you serialize an object to the string $ S, then remove this object, then counter the serialization

Objects to $ OBJ, you can still call the object's method function. But I don't recommend this method, because

(a) This feature is not necessarily supported in the future (b) This leads to an illusion, if you save a serialized object to magnetic

Disc and exit the program. When you re-run this script, you cannot deactivate this object and want the object.

The function is still valid because the serialized strings do not represent any member functions. Finally, serialization

The member variables of the saved object are very useful in PHP, just this. (You can serialize the joint array and number

Enter it 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 documentation). This causes $ OBJ2-> X.

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 you because it will get dirty. Clean document.

I hope PHP will fully support serialization in the future.

- Page 7 -

Use classes to manipulate save data

PHP and object-oriented programming a better place is that you are easy to define classes to manipulate something.

And call the appropriate class when needed. Suppose there is an HTML file, you need to select the product

ID number to select a product, your data is saved in the database, and you want to display product information,

Such as prices, etc. You have different kinds of products, the same actions have different meanings for different products.

For example, showing a sound means playing it, and it may be a storage for other products.

Picture of a database. You can use object-oriented programming and PHP to reach, code is less but better.

Define a class, define the method you should have, then define the class of each product by inheritance

(SoundItem class, ViewableItem class, etc.), redefine the method of each product class, make it

As you need. Give each product according to the product type field of the table you save in the database.

Type Defines a class, a typical product table should have a field (id, type, price, description, etc.).

Get the type information from the table of the database, then instantiate the object of the corresponding class:

$ OBJ = New $ TYPE ();

$ obj-> action ();

?>

This is the feature of PHP comparison, you can call $ OBJ's display method or other method without deactivation

Type of icons. With this technology, when you add a new type of object, you don't need to modify it.

script. This method is a bit power, which is to define all the methods that should have, regardless of its type,

After different classes in different classes, you can use them for different types of objects in the script, no IF, no two programmers in the same file, always happy. you believe

Is this happy? Maintenance cost is small and reuse it?

If you lead a group of programmers, the best way is to divide the task, each person can bear some kind of class and object

responsibility. Internationalization can be solved with the same technique to make the appropriate class corresponding to the different languages ​​selected by users.

and many more.

Copy and clone

When you create an object $ OBJ, you can use $ Obj2 = $ OBJ to copy an object, new

The object is a copy of $ OBJ (not a reference), so there is a new object in the assignment of $ OBJ.

status. Sometimes you don't want to do this, just want to create and OBJ's same new object, call the structure of the new object

The product is like you have used the new command. This can be serially connected and used by PHP and

He must be inherited from the base class.

- Page 8 -

Dangerous zone

When you serialize an object, you get a string with a specific format, if you have a curiosity, you can

Can you explore the secrets, there is a thing in the string is the name of the class, you can solve it:

$ HERRING = Serialize ($ OBJ);

$ vec = evLode (:, $ HERRING);

$ nam = str_replace ("" "" ,, $ vec [2]);

?>

Suppose you create a class "universe" and make all classes inherited from "universe", you can

Define a clone in "universe":

Class universe {

Function clone () {

$ HERRING = Serialize ($ this);

$ vec = evLode (:, $ HERRING);

$ nam = str_replace ("" "" ,, $ vec [2]);

$ RET = New $ NAM;

Return $ RET;

}

}

// Then:

$ obj = new thing ";

// Something Extends Universe !!

$ other = $ obj-> clone ();

?>

What you get is that the new object of class Something is as used as New, and the constructor is called.

and many more. I don't know if it is useful for you, this is a good practice, Universe class knows

Its inheritance class name. For you, the only restriction is your imagination! ! !

Note: I am using php4, some things in the article may not be suitable for PHP3.

- Page 9 -

-end-

Excerpt from:

www.linuxbyte.net

转载请注明原文地址:https://www.9cbs.com/read-112372.html

New Post(0)