Object-oriented Programming in PHP: A way to a large PHP project _php tutorial

Source: Internet
Author: User
This article describes object-oriented programming (OOP) in PHP. I'll show you how to use object-oriented concepts to compile less code but better programs. Good luck to all of you.

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

Ways to encapsulate a class in PHP:

Class Something {
In OOP classes is 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 good standard.

The data members of a class in PHP use the "var" definition, and the data member is not typed until it is assigned a value. A data member may be an integer, an array, a union array (associative array), or even an object. method is defined in a class as a function, in the method to access the data members, you must use $this->name, otherwise, the method is a function of the local variables.

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 variable in the object (not the Class) obj, and then GetX returns the value 5.

You can also use object references to access member variables, for example: $obj->x=6; However, this is not a good method of object-oriented programming. I insist. You should use the member function to set the value of the member variable and to read the member variable through the 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 use lowercase to seperate
Words in the method name Example Getvalueofarea ()
$this->y= $v;
}

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

Such "another" objects have member variables and method functions that are used by the parent class, plus their own
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 have a class inherit multiple classes.

You can redefine the method in the inheriting class, and if we redefine the GetX in "another", then we can no longer access 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, the variable that inherits the class will hide the variable with the same name as the parent class.

You can define a class's constructor, which is a member function that has the same name as the class, and is called when you create an 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 objects in the following ways:

$obj =new Something (6);

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

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 parameter is defined in the same way as C + +, so you cannot pass a value to Y but let X take the default value, the pass of the argument is left to right, and the function uses the default parameter when there are no more 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 called, which is the feature of PHP's different object-oriented languages, because the constructor call chain is an object-oriented programming feature. If you want to call the constructor of the base class, you have to explicitly call it in the constructor of the inheriting class. This allows it to work because the methods of the parent class in the inheriting class are all available.

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

A good mechanism in object-oriented programming is the use of abstract classes, which are classes that cannot be instantiated but are used to define interfaces for inheriting classes. Designers often use abstract classes to force programmers to inherit only from specific base classes, so they can determine what functionality is required for the 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 make sure that it cannot be instantiated by invoking "die" in the constructor, and now define the function of the abstract class and call "die" in each function, and if the programmer does not want to redefine the function of the base class directly in the inheriting class, it will produce an error. In addition, you need to be sure that because PHP has no type, some objects are created from inherited classes inherited from the base class, so add a method in the base class to discern the class (return "some identities") and verify this, when you receive an object as a parameter to come in handy. But it doesn't work for a rogue program because he can redefine the function in an inherited class, which usually works only for lazy programmers. Of course, the best way is to prevent the program from contacting the base class code that only provides the interface.

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

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 arguments). A small door can do this:

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

function Myclass1 ($x) {
Code
}

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

This method can partially achieve the purpose of overloading.

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

It feels good!

Polymorphism

Polymorphism is defined as when an object is passed as a parameter at run time, the object can determine the ability to invoke that method. For example, using a class to define the method "draw", the inheriting class redefined the "draw" behavior to draw a circle or a square, so you have a function with the parameter x, which can be called $x->draw () in the function. If polymorphism is supported, then the call to the "draw" method depends on the type of Object X. Polymorphism is naturally supported in PHP (think about this when compiling in the C + + compiler, which method is called?). However, you do not know what the type of object 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);
$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 for PHP

The Pure object theory thinks that PHP is not a true object-oriented language, which is right. PHP is a mixed language, and you can use it in object-oriented or traditional architecture programming methods. For large projects, however, you might or would need to define classes using a purely object-oriented approach, and use only objects and classes in your project. Increasingly large projects benefit from using an object-oriented approach, and object-oriented engineering is very easy to maintain, easy to understand and reuse. This is the basic of software engineering. Using these concepts is the key to future success in web design.

Advanced object-oriented technology in PHP

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

Serialization

While PHP does not support persistent objects, persistent objects in object-oriented languages are objects that have been repeatedly called by the application to maintain their state and functionality, which means that there is a way to save the object to a file or database and then reload the object. This mechanism is called serialization. PHP has a serialization function that can be called in the object, and the serialization function returns a String representing the object. The serialization function then saves the member data instead of the member function.

In PHP4, if you serialize an object to a string $s and then delete the object and then crossdress the object to $obj, you can still call the object's method function. But I do not recommend this method, 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 crossdress this object and want the object's method function to still be valid because the serialized string does not represent any member function. Finally, it is very useful to serialize the member variables of the saved object in PHP, just so. (You can serialize union arrays and arrays into disk).

Example:

$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 member variables without member functions (according to the document). This leads to $obj 2->x is
The only way to access the member variable (because there is no member function).

There are some ways to solve this problem, but I'll leave it to you because it will stain this clean document.
I hope PHP will fully support serialization in the future.

Using classes to manipulate saved data

One of the better things about PHP and object-oriented programming is that you can easily define classes to manipulate something and invoke the appropriate class when needed. Suppose you have an HTML file, you need to select a product by selecting the ID number of the product, your data is saved in the database, and you want to display the product information such as price and so on. You have different kinds of products, the same action for different products have different meanings. For example, displaying a sound means playing it, while for other products it might be a picture stored in a database. You can do it with object-oriented programming and PHP, with less code but better.

Define a class, define the methods that the class should have, and then define the classes for each product by inheriting it (Sounditem class, Viewableitem class, and so on), redefining the methods of each product class so that they are what you need. Depending on the product Type field of the table you are saving in the database, define a class for each product type, 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 the PHP comparison feature, you can call $obj display method or other methods without having to control the type of the object. With this technique, when you add a new type of object, you don't need to modify the script. It's a bit of a power 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 they can be used in scripts for different types of objects, no if, no two programmers in the same file, always happy. Do you believe that programming is so happy? Low maintenance cost and reusable?

If you lead a group of programmers, the best way is to divide the task, each person can be responsible for a certain kind and object. Internationalization can be solved with the same technology, so that the appropriate classes correspond to the different languages selected 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, and the new object is a copy of the $obj (not a reference), so the new object is $obj with the new state after it is assigned. Sometimes you don't want to, just want to create the same new object as obj, and call the constructor of the new object as if you had used the command "new". 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.


A dangerous zone.

When you serialize an object, you get a string with a specific format, and if you're curious, you might find the secret, there's a thing in the string that's the name of the class, and you can untie 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 that the new object of Class Something is the same as if you use new, and the constructor is called and so on. I don't know if this is useful for you, this is a good practice, the Universe class knows the name of its inheriting class. For you, the only limit is your imagination!!!

Note: I'm using PHP4, and some things in the article may not be suitable for PHP3.

End

http://www.bkjia.com/PHPjc/317165.html www.bkjia.com true http://www.bkjia.com/PHPjc/317165.html techarticle This article describes object-oriented programming (OOP) in PHP. I'll show you how to use object-oriented concepts to compile less code but better programs. Good luck to all of you. An 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.