Classes and objects in PHP (translation: Midiguy)

Source: Internet
Author: User
Tags abstract define definition class definition functions new features variables variable
Object/**********************************************************
Translation: Midiguy
I also ask you to point out the wrong place
E-mail:midiguy@263.net
qq:5149927
***********************************************************/

The source of object-oriented programming comes from the idea that people look at things such as telephones and cars. Many programmers like to use "wrapping" or "inheriting" the words that confuse the average person when discussing object-oriented programming. We can relate the object-oriented concept to the natural object to understand its principle. Let's use the means of transportation for an analogy.

Design drawings

In order to build a transportation we need a design plan. This design can define the number, color and so on of the vehicle's wheels. A vehicle is defined by certain attributes and behaviors. In PHP, these properties and behaviors are called variables and methods (functions). A set of variables and methods that describe an object constitute a "class".

Expansion of the design diagram

Because there are different kinds of transportation, such as automobiles, bicycles and motorcycles. We need a method that allows us to add new features to various modes of transport while also using the general method of transportation, in other words, because "crawler" is used on all types of vehicles, we do not need to rewrite this method. We are able to "inherit" to accomplish this function. If we create a class that inherits from "vehicle", all the methods in the "Vehicle" class will be inherited by the "Car" class.

Abstract

Abstract purpose focuses only on the properties of a complex object, and in order to solve your problem, you need to build a sophisticated object. You can easily get a car with thousands of attributes, but if you need to design a program to keep a car dealer's catalog, you should only need a subset of more than 10 attributes. Such a car is abstracted into a car object suitable for programming use.

Packaging

Wrappers can hide the content tool mechanism of a set of methods and only provide users with a well-defined excuse. In object-oriented programming, packaging makes the object's data structure and methods grouped together. The easiest way to understand "packaging" is to refer to the telephone. Today, consumers can buy a wide variety of telephones, although the internal design methods of these telephones may be different, but all of these telephone machines are able to communicate through a standard public interface. This is the idea of packaging.

A class can define a new data type. PHP itself has variable types, such as string variables and floating-point type variables. But you can design your own data types such as ships, user reference manuals, databases, and so on. A class defines properties and behaviors (member variables and methods) of this data type. The following example shows how to define a class that contains properties and methods.

Let's take a look at the actual examples of our transportation.
<?php

/*
* * How to define a class
*/

Class Class_name
{
[var variable definition]
[Function method definition]
}

?>
----------Transportation------------
<?php

Class vehicle
{
/*
* * Properties
*/
var $property 1;
var $property 2;
var $property 3;

/*
* * method
*/
function Settires ($type)
{
if ($type = = \ "Firestone\")
{
$this->property1 = \ "must be a Ford suv\";
}
}

function Color ($col)
{
$this->property2 = $col;
}
}

?>

How to use a well-defined class

Once the class is defined, we can create an instance of it. To use just the example below, we create an instance of the "Vehicle" class below.

<?php

$myCar = new Vehicle ();
$myCar->settires (\ "firestone\");

?>


Using variables in a class

The biggest difference is in the kind of values that are owned by an object and object. A string variable is easy to understand because it has a value.
$myStr = \ "PHP stands for ... uh ... I forget\ ";

However, an object can have any kind of value
$myCar->year = 1988;
$myCar->value = 813.77;
$myCar->hasairbag = false;
$myCar->color = \ "Periwinkle\";

In PHP, all member variables of an object are publicly owned by default. There is no way to force an object's access attribute, but if you want a variable to be a private variable, we can do it in an emphatic way.

$this pointer
If you want to invoke the method of an object, you can use \ ' $this \ ' To call this object to specify the member variable of the instance. At first, you may not understand this, let's take a look at an example. First, let's say you have two cars.

$myCar = new Vehicle ();
$spousesCar = new Vehicle ();

Now you have two objects of the same class. You may have heard the saying, "Now you have two comprehensive variables of the same user-defined variable type." These are just different ways the talking OOP same.
Each variable, $myCar and $spousesCar, has a separate set of attributes for this class.

$myCar->property1;
These two are different.
$spousesCar->property1;

Even if property1 only occurs once in the class definition. You must be aware that it is only designed to form a new data type.
But within this class there is only one settires () function. When we use the following statement, how does it know who called it?

$myCar->settires (\ "firestone\");

Oh, now this $this is working. This object is automatically passed as a parameter when a specified object invokes a function inside the class. The use of $this is necessary for convenience. Look at the following example you should be able to understand.

$myCar->settires (\ "firestone\");

/*
* * method
*/
function Settires ($type)
{
if ($type = = \ "Firestone\")
{
$this->property1 = \ "must be a Ford suv\";
}
}
$this represents $myCar variable

$spousesCar->settires (\ "Goodyear\");

/*
* * method
*/
function Settires ($type)
{
if ($type = = \ "Firestone\")
{
$this->property1 = \ "must be a Ford suv\";
}
}
Now it represents $spousesCar.

Create a constructor

After an instance of a class is created, what happens if the developer wants to have a "default" function that can be invoked? This is where you use the constructor.
In fact, you simply have to define the name of the constructor as the name of the class to be implemented. Now every time you create an object of this class, this constructor method is invoked.

Inheritance of Classes

As we've said before, a class can inherit another class, but how do we take advantage of that? In a system, many variables play the same role, and only some of the roles are somewhat different, inheritance is very useful. Inheritance is a way in which a class can build itself with another class as a template. The inheriting class inherits the member variables and methods defined in the inherited class. Classes that extend or inherit are called subclasses. The inherited class is called a superclass or parent class. This enables different classes to function differently and does not affect existing code. Now let's take a look at an example.

Class Airplane {
var $tirePressure;
var $fuelLevel;
var $passengerLimit;

function takeoff () {
...
}

function Land () {
...
}

function Preflightcheck () {}
}

Class Sevenfortyseven extends Airplane {

function Preflightcheck () {
747 Aircraft takeoff preparation work
}
}

Class biplane extends Airplane {

function Preflightcheck () {
Two-wing aircraft take-off preparatory work
}
}


$planeArray [] = new biplane ();
$planeArray [] = new Sevenfortyseven ();
$planeArray [] = new Sevenfortyseven ();
$planeArray [] = new biplane ();

for ($x = 0; $x < count ($planeArray); $x + +) {
$currentPlane = $planeArray [$x];
if ($currentPlane->preflightcheck ()) {
$currentPlane->takeoff ();
No matter what type of plane it is, it will know it's going to take off.
} else {
Print \ "There was something wrong with the plane. \";
}
}

static method of Class

When dealing with objects of a class, you might put a function that is useful to the object in this class, instead of writing another special class. Such a function is called a static method. A good
The class should contain all useful (utility) functions.

Class Money {

function AddTax ($amount, $percent) {
return $amount + ($amount * $percent);
}


function ConvertCurrency ($amount, $from, $to) {
Find a conversion rate from $from to $to in the database
return $amount * $rate;
}

}

$total = Money::addtax ($subtotal, 6.5);

$yen = money::convertcurrency ($USD, \ "America\", \ "japan\");



Method Factory (Factory Methods)

Sometimes it's good to split the code into chunks to create objects. You can use a large number of classes, or you can use a class to determine the object's use of the Factory class (factory methods).
The factory class can help you organize your code effectively. In general, the factory class contains a larger transformation declaration and returns an instance of the appropriate object. Let's take a look at the C-scan
Miriam's example. There is an item base class, but there are also many subclasses that can be invoked for a wide variety of products (e.g. electronics, clothing ...). )。

Class Item {
var $price;
var $isTaxable;
var $properties;

function Getnewitem ($UPC) {
Connecting to a database
Find the type of $UPC and put it into the $type variable
Find the attributes of the $UPC and place them as $attrib variables;
return new $type ($attrib);
}
}

Class Produce extends Item {

function produce ($a) {
$this->properties = $a;
}


function Requiresscale () {
return true;
}
}


Class Hardlines extends Item {

function Hardlines ($a) {
$this->properties = $a;
}

function Requiressclae () {
return false;
}
}


while ($UPC = $scanner->next_code ()) {//Suppose that there is a scanner class

$z = Item::getnewitem ($UPC);

if ($z->requiresscale ()) {
echo \ "needs size!" \";
}

$subtotal + + $z->properties[\ "price\"];
}



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.