Object-oriented third major feature: polymorphic
Concept: When a parent class reference is directed to a subclass instance, the child class overrides the parent class function, which causes us to behave differently when using the reference to invoke the corresponding method
Condition: 1. Must have inheritance
2. Subclasses must override methods of the parent class
Polymorphism is not obvious in weakly typed language, it is obvious in strongly typed language, and it is not considered in PHP.
Class Ren
{
Public $name;
Public $sex;
function Say ()
{
echo "Hello";
}
}
Class China extends Ren
{
function Say ()
{
echo "Hello";
}
}
$r =new Ren ();
$r 1 =new China ();
Polymorphism in a strongly typed language can refer to an instance of a subclass in a parent class, and PHP does not have to specify the type of the variable, polymorphism is not obvious.
function Overloading :
1. The method name must be the same
2. The number of parameters in the function is different
3. If the number of parameters is the same, the type is different
function overloading is only available in strongly typed languages, not in weakly typed languages
PHP is a weakly typed language, PHP has a variable parameter function, and does not specify the parameter type, does not satisfy the function overloading condition.
function Say ()
{
echo "Hello";
}
function say ($a)
{
echo $a. " Hello ";
}
function say ($a, $b)
{
echo $a. $b. " Hello ";
}
Three say () methods, with different number of parameters, called functions are also different.
__tostring () method : Some description of the output class
function __tostring ()
{
Return "This object contains the variable name and sex, a say method";
}
$r = new Ren ();
Echo $r; Output return value
Clone of the object:
$r =new Ren ();
$r->name= "Zhang San";
$r 1 =clone $r; Cloning objects
Var_dump ($r 1);
When cloning, you want to add something special to the new object of the clone, you need to include the __clone method in the Ren class
function __clone ()
{
$this->name= "John Doe"; $this is a replica (a new object after cloning)
}
Echo $r->name;
Echo $r 1->name;
Output: Dick and Harry
PHP classes and Objects (ii)