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.'
关于初学者的 PHP 类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5199862/