初学者的PHP类继承

前端之家收集整理的这篇文章主要介绍了初学者的PHP类继承前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
class User{
    public $company_name;
}

class Employer extends User{
    public $fname;
    public $sname;
}

这是我创建的test.PHP.我已经包含了类文件.

$employer = new Employer();
$user = new User();
$employer->company_name = "Company name is ";
echo $user->company_name;

当我打印名称没有任何反应时,请让我知道我的代码有什么问题.

您的Employer类扩展了您的User类,但是当您创建$user和$employer对象时,它们是独立的实体且不相关.

想想你的对象:

$employer = new Employer();
// You now have $employer object with the following properties:
// $employer->company_name;
// $employer->fname;
// $employer->sname;

$user = new User();
// You now have $user object with the following properties:
// $user->company_name;

$employer->company_name = "Company name is ";
// You now have $employer object with the following properties:
// $employer->company_name = 'Company name is ';
// $employer->fname;
// $employer->sname;

echo $user->company_name;
// You currently have $user object with the following properties:
// $user->company_name;  /* no value to echo! */

如果要使用继承的属性,它的工作方式更像:

class User{
    public $company_name;

    function PrintCompanyName(){
        echo 'My company name is ' . $this->company_name;
    }
}

class Employer extends User{
    public $fname;
    public $sname;
}

$employer = new Employer();
$employer->company_name = 'Rasta Pasta';
$employer->PrintCompanyName();  //echoes 'My company name is Rasta Pasta.'
原文链接:https://www.f2er.com/php/136752.html

猜你在找的PHP相关文章