Learn and be familiar with the concept of class with the right car object

Source: Internet
Author: User
Tags add object functions gety integer return access
Object | Concept A lot of books talk about class always like to take the car as an example, but some examples are really smelly and rotten fraught, cheat money, ruin the future, retarded low-level to make up a what set_color () function to teach people. It was a waste of good things. Today, I saw a victim in phpx.com and couldn't help but spend two hours writing this tutorial.

Gossip less said, we come to the serious, our car is not just let people figure tutu color is over (only the color of the car is waste). Our car is not only capable of running around, but also equipped with advanced GPS Global Positioning System, oil meter, odometer. With object-oriented technology, it's not hard to steer a car like this.

For example, you should first provide some background material. We have a car, you can in a map with XY coordinates in accordance with the direction of arbitrary driving, you can set the direction of the car and distance, the car will report to you its coordinate position.

In fact, learning class should be the same as we learn other things, from learning to use the beginning, and then learn his principles. So let's start by getting to know how to drive a car like this correctly:


<?php
$startPoint = & New Position (3,9); Initial starting point coordinates x=3,y=9

$myCar = & New Car ($startPoint); I got a new car, the initial fuel 500 liters, the departure location $startpoint.

$myCar->setheading (' s '); Set direction for the trolley s: South N: North W: West E: Orient.

if ($myCar->run (100))//Then let the car run 100 km, if the successful completion of the task shows the amount of fuel. If we give up halfway, we display the alert information.
{
Print (' <br><b> car is all right, there is still fuel: '. $myCar->getgas (). ' </b> ")//Get fuel number
}
Else
{
Print (' <br><b> car problem: '. $myCar->getwarning (). ' </b> ")//Display alert information
}

$myPosition = $myCar->getposition ();//Get the current position of the car

Print (' <br> my car now <br> X: '. $myPosition->getx (). ' Y: '. $myPosition->gety ())//show the coordinate position of the car
?>
First make a car for yourself, and equip him with a locating object Position. Then set the direction and let the car run. Finally check and output the location of the car. Is it complicated? Is it hard to understand? Although here we have two objects (classes): Car and Position but I'm sure even beginners won't find the above code difficult.

We learn how to drive, and then take a closer look at how the object of the car works. Defining an object is simply a matter of a keyword class and a pair of {}, so we define these two objects:

Class Car {}
Class position{}

Of course, there's nothing to do with just two classes, we also need to add some function to them, starting from the car, we need to be able to set the direction of the car and let the car run so we add two methods, that is, 2 functions except that these two functions are included in the car object only through the car object can be used.

Setheading ()
Run ()
Class car
{
function setheading ($direction)
{

}

function Run ($km)
{

}
}

Special tip: The trick to designing a good class is to start with how it is used, that is, to first consider what the object should be, rather than determine what attributes it has.
In order to better understand the situation of the car we also need these methods:
Getgas () Get the current fuel number of the trolley
GetPosition () Get the current position of the trolley
Getwarning () Alert information
In order to complete these functions our car also needs its own oil meter, alarm message, and locator. We added these to the car class, and we added an initialization function to the class, which has the same function name as the class name, so there's a general framework.


<?php
Class car
{
/**
* The amount of petrol in the car
*
* @var
* @access
*/
var $gas;

/**
* Mileage Record
*
* @var
* @access
*/
var $meter;

/**
* Position of the car (automatic control by GPS)
*
* @var Object position
* @access Private
*/
var $position;

/**
* Engine fuel consumption per 1 kilometers, this car is 0.1 liters
*
* @var Integer
* @access Private
*/
var $engine = 0.1;

/**
* Alert Information
*
* @var
* @access
*/
var $warning;

/**
The initialization of the car. The new car, of course.
1, add gasoline.
2, the odometer to zero.
3, clear alert information.
4, set the starting position.
*/
function car ($gas,& $position)
{
$this->gas= $gas; Add Gasoline
$this->meter = 0;
$this->warning = '; Clear Alert Information
$this->position = $position; Set departure Location
}

function getwarning ()//Return alert information
{
return $this->warning;
}

function Getgas ()//Return to Gasoline meter index
{
return $this->gas;
}

function &getposition ()
{
return $this->position; Return to the position of the current car
}

function setheading ($direction = ' E ')
{

}

/**
* Start the car
* @access Public
* @param of INT km
*/
function Run ($km)
{

}

}
?>
At this time the most critical two methods setheading and run became simple, because the car equipped with Position object $this->position, so about the coordinates of the positioning of the matter it also need not tube, to Position object Well, he himself as long as the management from Own oil meter, the odometer on it. The car class that is finished becomes this way:


<?php
Class car
{
/**
* The amount of petrol in the car
*
* @var
* @access
*/
var $gas;

/**
* Mileage Record
*
* @var
* @access
*/
var $meter;

/**
* Position of the car (automatic control by GPS)
*
* @var Object position
* @access Private
*/
var $position;

/**
* Engine fuel consumption per 1 kilometers, this car is 0.1 liters
*
* @var Integer
* @access Private
*/
var $engine = 0.1;

/**
* Alert Information
*
* @var
* @access
*/
var $warning;


/**
The initialization of the car. The new car, of course.
1. Fill up with petrol.
2, the odometer to zero.
3, clear alert information.
4, set the starting position.
*/
function car ($gas,& $position)
{
$this->gas= $gas; Fill up the gas.
$this->meter = 0;
$this->warning = '; Clear Alert Information
$this->position = $position; Set initial position
}

function getwarning ()//Return alert information
{
return $this->warning;
}

function Getgas ()//Return to Gasoline meter index
{
return $this->gas;
}

function &getposition ()
{
return $this->position; Return to the position of the current car
}

function setheading ($direction = ' E ')
{
$this->position->setdirection ($direction); Because of the use of the position object, the car does not need to worry about the XY coordinate value, to the Position object.
}

/**
* Start the car
* @access Public
* @param of INT km
*/

function Run ($km)
{
$goodRunFlag = true;//Whether the task completed successfully.
$maxDistance = $this->gas/$this->engine; The maximum distance a car can run.

if (($maxDistance) < $km)
{
$this->warning = ' no petrol! '//Set warning message, how far you can run.
$goodRunFlag = false;//But the task must not be completed.
}
Else
{
$maxDistance = $km; No problem, you can stop to have a rest after you finish the task.
}
$this->position->move ($maxDistance)//In the coordinates moved by the position object to complete, the car as long as the responsibility of their own fuel consumption and kilometer table can be.
$this->gas = $maxDistance * $this->engine;//consumes petrol
$this->meter + + $maxDistance; Increase kilometer table count
return $goodRunFlag;
}
}
?>
Speaking of which, I think my article should be over. Don't worry, I certainly remember Position class has not finished, but with the example of the car above Position should be very simple, if you understand the class of the car, now is your time to show your skill, you finish this Position object, I believe you can do it (which is the beauty of object-oriented and encapsulation). You need to remember to start with the position approach:


GetX ()
GetY ()
Move ()
Setdirection ()
A class is a kind of thing, it can be specific (car) or abstract (Position), we simplify the use and operation by encapsulation just as we use TV, mobile phone is not complicated.

A good introductory tutorial should

Vivid and true examples.
Not only provides the correct concept of variables and function naming, function encapsulation and invocation also value of learning.
Even if you're familiar with object-oriented programming, you don't think there's anything wrong with the original example.
If you finish reading the tutorial, you will be able to deeply understand the beauty of the tutorial, greatly reducing the chance of detours.
Good code can be read like a book, you think?


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.