Php object-oriented BASICS (2) and php object-oriented Basics
Three features of object-oriented
1. Encapsulation
Objective: To make the class more secure
Practice:
A. Change member variables to private
B. Make a member Method for indirect access
C. add restrictions to this method.
Class Ren
{
Private $ age; // between 18 and 50
Private $ name;
// Magic method, assign a value to the variable
Function _ set ($ n, $ v)
{
If ($ n = "age ")
{
If ($ n >=18 & $ n <= 50)
{
$ This-> $ n = $ v;
}
}
Else
{
$ This-> $ n = $ v;
}
}
// Magic mode, variable value
Function _ get ($ n)
{
Return $ this-> $ n;
}
// The following method applies only to one or two variables:
/* Function setAge ($ n)
{
If ($ n >=18 & $ n <= 50)
{
$ This-> age = $ n;
}
}
Function getAge ()
{
Return $ this-> age;
}*/
}
$ R = new Ren ();
$ R->__ set ("age", 20 );
$ R-> age = 20;
$ R-> name = "James ";
Var_dump ($ r );
2. Inheritance
Subclass can inherit everything from the parent class (except for Private Members)
Features: single inheritance
Class Ren
{
Private $ name;
Function Run ()
{
Echo "running: <br> ";
}
}
Class China extends Ren // who inherits extends
{
// Override
Function Run ()
{
Parent: Run ();
Echo "Chinese running ";
}
}
$ C = new China ();
$ C-> Run ();
Var_dump ($ c );
3. Polymorphism(Weak languages cannot implement polymorphism)
Definition: when a parent class references a subclass instance, the method of the parent class is overwritten by the subclass.