当前位置:网站首页>[PHP] PHP polymorphism

[PHP] PHP polymorphism

2022-06-22 23:46:00 weixin_ forty-three million two hundred and twenty-four thousan

What does polymorphism mean : When objects of the same class receive the same message , We'll get different results . And the news is unpredictable . polymorphic , seeing the name of a thing one thinks of its function , It's a variety of states , That is, a variety of results .

example 1

<?php 

class employee{
    protected function working(){
        echo ' This method requires overloading ';
    }
}

class teacher extends employee{
    public function working(){
        echo ' Teach ';
    }
}

class coder extends employee{
        public function working(){
        echo ' Write code ';
    }
}

function doprint($obj){
    if(get_class($obj) == 'employee'){
        echo 'Error';
    }else{
        $obj->working();
    }
}

doprint(new teacher());
doprint(new coder());
doprint(new employee());

example 2

<?php 

interface employee{
    public function working();
}

class teacher implements employee{
    public function working(){
        echo ' Teach ';
    }
}

class coder implements employee{
        public function working(){
        echo ' Write code ';
    }
}

function doprint(employee $i){
    $i->working();
}

$a = new teacher;
$b = new coder;
doprint($a);
doprint($b);

example 2 And example 1 It doesn't make much difference , But in the code doprint The parameter of the function is a variable of interface type , accord with “ The same type , Different results ” This condition , A general characteristic of polymorphism , So it's polymorphism
example 1 If you put doprint Functional obj Parameters are treated as a type ( Think of all weak types as one type ), That can also be considered polymorphic , Otherwise, it's not
The key to distinguishing whether an object is polymorphic is whether the object belongs to the same type
php In, the parent and child classes are treated as “ Stepfather ” and “ Stepson ” Relationship , They are inherited , But there is no blood relationship . Therefore, a child class cannot be transformed upward into a parent class , Thus losing the most typical characteristic of polymorphism

原网站

版权声明
本文为[weixin_ forty-three million two hundred and twenty-four thousan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222124162414.html