gpt4 book ai didi

初学者的 PHP 类继承

转载 作者:可可西里 更新时间:2023-11-01 12:41:33 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com