Learn and familiarize yourself with the concept of class with the correct car object
Many books always like to use cars as examples when it comes to classes, but some examples are really bad and bad, cheating people's money, destroying people's future, and being so mentally retarded that they make up a set_color() function to teach people. It's really a waste of money. I saw another victim today and couldn't help but spend two hours writing this tutorial.
Let’s talk less about it. Let’s be serious. Our car is not just a matter of just letting the picture color (those who can only picture color are scrap cars). Our car is not only able to run around, but also equipped with advanced GPS global positioning system, fuel meter, and odometer. Thanks to the use of object-oriented technology, it is not difficult to drive such a small car.
To give an example, we must first provide some background materials. We have a car that can drive arbitrarily in the southeast, southwest and northwest directions on a map with xy coordinates. You can set the direction and distance of the car, and the car will report its coordinate position to you.
In fact, learning should be the same as we learn other things, starting from learning and using them, and then learning its principles. So let's first get familiar with how to drive such a small car correctly:
Copy the codeThe code is as follows:
<?php
$startPoint = & new Position(3,9); //The coordinates of the initial starting point x=3,y=9
$myCar = & new Car(500,$startPoint); //I get a new car with 500 liters of initial fuel, and the departure point is $startPoint.
$myCar->setHeading('s'); //Set the direction for the car s: South n: North w: West e: East.
if($myCar->run(100)) //Then let the car run 100 kilometers, and the fuel volume will be displayed if the task is completed successfully. If we give up halfway, we display an alarm message.
{
print('<br><b>The car is all right, and there is still fuel at present: '.$myCar->getGas().'</b>');//Get the fuel count
}
else
{
print('<br><b>There is a problem with the car: '.$myCar->getWarning().'</b>');//Show the alarm message
}
$myPosition=$myCar->getPosition();//Get the current position of the car
print('<br>My car is now<br> X:'.$myPosition->getX().'Y:'.$myPosition->getY());//Show the coordinate position of the car
?>
First, build a car for yourself and equip him with a positioning object. Then set the direction and let the car run. Finally, check and output the position of the car. Is it complicated? Is it difficult to understand? Although we used two objects (classes): Car and Position, I believe that even beginners will not find the above code difficult.
After we learn how to drive, let’s take a closer look at how the car’s partner works. Defining an object is actually very simple. Just use a keyword class and a pair of {}, so we define these two objects in this way:
class Car {}
class Position{}
Of course, just two such classes can't do anything. We also need to add some functions to them. Start with the car. We need to be able to set the direction for the car and let the car run. So we add two methods, that is, two functions, but these two functions are included in the car object and can only be used through the car object.
Copy the codeThe code is as follows:
setHeading()
run()
class Car
{
function setHeading($direction)
{
}
function run($km)
{
}
}
Special tip: The trick to design a good class is to start with how to use it, that is, consider what methods should be used for this object, rather than determining what properties it has first.
In order to better understand the situation of the car, we also need these methods:
getGas() Gets the current fuel count of the car
getPosition() Gets the current position of the car
getWarning() Alarm Information
To complete these functions, our car also needs its own fuel gauge, alarm message, and positioner. We also add these to the Car class, and we also add an initialized function to this class. This function name is the same as the class name, so that there is a general framework.
Copy the codeThe code is as follows:
<?php
class Car
{
/**
* The amount of gasoline in the car
*
*@var
*@access
*/
var $gas;
/**
* Mileage record
*
*@var
*@access
*/
var $meter;
/**
* Car location (automatically controlled by GPS)
*
*@var Object position
*@access private
*/
var $position;
/**
* The engine consumes fuel per 1 km, this car is 0.1 liter
*
*@var Integer
*@access private
*/
var $engine=0.1;
/**
* Alarm information
*
*@var
*@access
*/
var $warning;
/**
Initialization of the car. Of course, new cars need to be released
1. Add gasoline.
2. The odometer returns to zero.
3. Clear the alarm information.
4. Set the departure position.
*/
function Car($gas,&$position)
{
$this->gas= $gas; //Add gasoline
$this->meter = 0;
$this->warning =''; //Clear the alarm information
$this->position = $position; //Set the departure position
}
function getWarning() //Return alert information
{
return $this->warning;
}
function getGas() //Return gasoline meter index
{
return $this->gas;
}
function &getPosition()
{
return $this->position; //Return to the current car position
}
function setHeading($direction='e')
{
}
/**
* Start the car
*@access public
*@param INT kilometers
*/
function run($km)
{
}
}
?>
At this time, the two most critical methods setHeading and run become simple. Since the car is equipped with the Position object $this->position, it doesn’t have to worry about coordinate positioning anymore. Leave it to the Position object. He just needs to manage his own oil meter and the odometer. After completion, the Car class becomes like this:
Copy the codeThe code is as follows:
<?php
class Car
{
/**
* The amount of gasoline in the car
*
*@var
*@access
*/
var $gas;
/**
* Mileage record
*
*@var
*@access
*/
var $meter;
/**
* Car location (automatically controlled by GPS)
*
*@var Object position
*@access private
*/
var $position;
/**
* The engine consumes fuel per 1 km, this car is 0.1 liter
*
*@var Integer
*@access private
*/
var $engine=0.1;
/**
* Alarm information
*
*@var
*@access
*/
var $warning;
/**
Initialization of the car. Of course, new cars need to be released
1. Full of gasoline.
2. The odometer returns to zero.
3. Clear the alarm information.
4. Set the departure position.
*/
function Car($gas,&$position)
{
$this->gas= $gas; //Fill gasoline
$this->meter = 0;
$this->warning =''; //Clear the alarm information
$this->position = $position; //Set the initial position
}
function getWarning() //Return alert information
{
return $this->warning;
}
function getGas() //Return gasoline meter index
{
return $this->gas;
}
function &getPosition()
{
return $this->position; //Return to the current car position
}
function setHeading($direction='e')
{
$this->position->setDirection($direction); //Because the Position object is used, the car does not need to worry about the XY coordinate value by itself, so leave it to the Position object.
}
/**
* Start the car
*@access public
*@param INT kilometers
*/
function run($km)
{
$goodRunFlag = true;//Whether the task is completed successfully.
$maxDistance = $this->gas/$this->engine; //The maximum distance a car can run.
if(($maxDistance)<$km)
{
$this->warning = 'No gasoline anymore! ';//Set warning messages, run as far as you can.
$goodRunFlag = false;//But the task will definitely not be completed.
}
else
{
$maxDistance=$km; //No problem, you can stop and rest after completing the task.
}
$this->position->move($maxDistance);//Move on coordinates is done by the Position object. The car only needs to be responsible for its own fuel consumption and kilometer table.
$this->gas -= $maxDistance*$this->engine;//Consumes gasoline
$this->meter += $maxDistance; //Increase the count of the kilometer table
return $goodRunFlag;
}
}
?>
Having said this, I think my article should end. Don't worry, of course I still remember that the Position class has not been completed yet, but with the example of the car above, Position should be very simple. If you understand the class of this car, now is the time for you to show your skills. You can complete this Position object. I believe you can complete it (actually this is the beauty of object-oriented and encapsulation). You need to remember to start designing with Position method, for example:
getX()
getY()
move()
setDirection()
The so-called class refers to a certain type of thing. It can be concrete (Car) or abstract (Position). We simplify the use and operation through encapsulation, just like when we use TV and mobile phones, it is not complicated at all.
A good introductory tutorial should
A vivid and realistic example.
Not only provides the correct concept, it also learns value in variables and function naming, function encapsulation and call.
Even if you are familiar with object-oriented programming, you will not think that there is anything wrong with the original example.
If you finish reading the tutorial, you will definitely be able to deeply understand the beauty of the tutorial, greatly reducing the chance of taking detours.
Good code can be understood like a book, what do you think?
Previous page12Read the full text