Chapter 3 Object Basics
Topics:
- Declaring classes and instantiating objects
- How does constructor works
- Class types
- Inheritance
- Visibility: public, protected, private
1. Classes and Objects
** Class is a code template used to generate objects **
** Object is the data that has been structured according to the template defined in a class **
class Class(){
}
$object1 = new Class();
$object2 = new Class();
$object1
and $object2
are functionally identical, but they are different objects.
If we print out the $object1
and $object2
:
var_dump($object1);
var_dump($object2);
//this will be the results:
object(Class)#1 (0) { }
object(Class)#2 (0) { }
#1
and #2
are the identifiers of the objects, which indicate these two objects are different.
Class can contain properties and methods. Based on the visibility of the property, it can be accessed from the outside of the class or not.
class Class(){
public title = 'old value';
}
//this is how to access an public property from the outside of the class
$object1->title = "new value";
** Property can also be added dynamically, but is usually considered bad practice in object-oriented programming **
//add new property that has not defined in the class, but usually not a good practice
$object->name = 'new name';
$this
** is a pseudo variable that indicates the current instance. ** For example, $this->name
means the $name
property of the current instance
2. Constructor
** Constructor is the method that will be automatically invoked when an object is created. ** It ensures that some of the essential properties are set and necessary preliminary work is completed.
class Student {
public $name;
public $age;
public $grade;
function __construct($name, $age, $grade){
$this->name = $name;
$this->age = $age;
$this->grade = $grade;
}
function getStudent(){
echo "$this->name is $this->age years old, and has a grade of $this->grade.";
}
}
//this will cause php warning that you didn't set the 1st, 2nd and 3rd parameter of the construct method
$Sam = new Student();
//this is the correct way to create an object of the student class
$john = new Student("John","12","A");
$john->getStudent();
The above code will produce the following text:
John is 12 years old, and has a grade of A.
3. Arguments and Types
** Primitive Types: bool, integer, double, string, object, array, resource, null **
** An object's type is its class. ** Therefore, it is necessary to ensure the right type of object is passed around.This can be done by type hint.
For example, if there are two classes, and one requires another to be its parameter:
class Student {
public $name;
public $age;
public $grade;
function __construct($name, $age, $grade){
$this->name = $name;
$this->age = $age;
$this->grade = $grade;
}
}
class Upperclass{
//without type hint, the wrong type of object can be passed into this function
function isUpper($Student) {
if($Student->age > 12)
echo "This is an upper class student."
else
echo "This is a lower class student."
}
//with type hint, if wrong object is passed into this function,
//a fatal error will occur:
//Argument 1 passed to Upperclass::goodStudent() must be an instance of
Student, instance of Wrong given ...
function goodStudent(Student $Student) {
if($Student->grade == 'A' || $Student->grade == 'B')
echo "This is good student."
else if($Student->grade == 'F')
echo "This student needs to pay some effort."
else
echo "This student performs normally."
}
}
** Type hint doesn't work on types like string, int, double...however it does work on array **
function setArray(array $array){}
For integers, strings, and etc., you have to use checking function like is_int()
You can also demand a null default value:
function setName($name = null){}
4. Inheritance
** Inheritance is the means by which one or more classes can be derived from a base class. **
** Inheritance is particularly useful when dealing with objects that have different properties but lie inside the same class. ** For example, bicycles and cars are both transportations, but they have different number of wheels.
class Transportations{
private $speed;
private $weight;
private $color;
function _construct($speed, $weight, $color){
$this->speed = $speed;
$this->weight = $weight;
$this->color = $color;
}
}
class Bicycle extends Transportations{
private $wheel = 2;
function wheelNumber(){
return $this->wheel;
}
}
class Car extends Transportations{
private $wheel = 4;
function wheelNumber(){
return $this->wheel;
}
}
Constructors and Inheritance
** The above code doesn't declare a construct function in the child classes, thus the parent class construct method will be called. **
** However, when you define a constructor in a child class, you become responsible for passing any arguments on to the parent. If you fail to do this, you can end up with a partially constructed object. **
** To refer to a method in the context of a class rather than an object you use :: rather than ->. So: parent::__construct()
**
PS: As a good rule, avoiding giving parent class any specific knowledge about its children.
Overridden Method
** It is usually better to extend a method rather than obliterate it when you override a method **
class Transportations{
private $speed;
private $weight;
private $color;
function _construct($speed, $weight, $color){
$this->speed = $speed;
$this->weight = $weight;
$this->color = $color;
}
function getTransportation(){
$transportation = "This transportation has $this->weight and is $this->color. It can travel with a speed $this->speed.";
return $transportation;
}
}
class Bicycle extends Transportations{
private $wheel = 2;
function wheelNumber(){
return $this->wheel;
}
function getTransportation(){
$bicycle = "This bicycle is $this->weight and has a $this->color color. It can travel with a speed $this->speed.";
return $bicycle;
}
}
class Car extends Transportations{
private $wheel = 4;
function wheelNumber(){
return $this->wheel;
}
function getTransportation(){
$car = "This car is $this->weight and has a $this->color color. It can travel with a speed $this->speed.";
return $car;
}
}
The children classes override the function getTransportation()
.
5. Visibility: Public, Private and Protected
Scale | Difference |
---|---|
Public | Public properties and methods can be accessed from any context |
Private | Private properties and methods can only be accessed from within the enclosing class. Even subclasses have no access |
Protected | Protected properties and methods can only be accessed from within the enclosing class or from a subclass. No external code is granted access |
Visibility is used to prevent bad access from outside of the world.** As a general rule, make properties private or protected at first and relax the restriction only as needed. Any method that provides local functionality for other methods in the class should also be kept as private or protected. **
The way to access a private property is to use the defined public method. If there is no public method to use, then that property is probably designed to not to be accessed by the outside world.
class Transportations{
private $speed;
private $weight;
private $color;
function _construct($speed, $weight, $color){
$this->speed = $speed;
$this->weight = $weight;
$this->color = $color;
}
function getTransportation(){
$transportation = "This transportation has $this->weight and is $this->color. It can travel with a speed $this->speed.";
return $transportation;
}
}
$car = new Transportation('100km/h','1 ton', 'white');
//it's illegal to access the properties like this
echo $car->speed;
//in order to get the information of the car, you have to use the method getTransportation();
$information = $car->getTransportation();
echo $information;
网友评论