PHP类继承初学者 [英] PHP Class Inheritance for Beginners
本文介绍了PHP类继承初学者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class User{
public $company_name;
}
class Employer extends User{
public $fname;
public $sname;
}
这是我创建的test.php。我已包含类文件。
this is the test.php i have created. I have included the class file.
$employer = new Employer();
$user = new User();
$employer->company_name = "Company name is ";
echo $user->company_name;
当我打印名字没有发生任何事情,请让我知道我的代码是什么。 / p>
When i print the name nothing happens, please let me know what is the wrong with my code.
推荐答案
您的 Employer
类扩展了 / code>类,但是当您创建
$ user
和 $ employer
对象时,它们是单独的实体, 。
Your Employer
class extends your User
class but when you create your $user
and $employer
objects they are separate entities and unrelated.
想象你的对象:
$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! */
如果要使用继承的属性,它的工作原理更类似:
If you want to use inherited properties, it works more like this:
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类继承初学者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文