class User{
public $company_name;
}
class Employer extends User{
public $fname;
public $sname;
}
Run Code Online (Sandbox Code Playgroud)
这是我创建的test.php.我已经包含了类文件.
$employer = new Employer();
$user = new User();
$employer->company_name = "Company name is ";
echo $user->company_name;
Run Code Online (Sandbox Code Playgroud)
当我打印名称没有任何反应时,请让我知道我的代码有什么问题.
Far*_*ray 16
你的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! */
Run Code Online (Sandbox Code Playgroud)
如果要使用继承的属性,它的工作方式更像是:
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.'
Run Code Online (Sandbox Code Playgroud)