gpt4 book ai didi

php - 使用构造函数初始化变量的正确方法

转载 作者:行者123 更新时间:2023-12-02 21:27:44 26 4
gpt4 key购买 nike

这是使用构造函数初始化变量的正确方法吗?

class Customer
{
public $custId;
public $custName;
function _construct()
{
$this->custId = 'Eazy01';
$this->custName = 'EazyLearnKaloor';
}

function DisplayDetails()
{
echo "$custId<br>";
echo "$custName";
}
}

$obj = new Customer();
$obj->DisplayDetails();

最佳答案

您需要使用双下疮,如__construct()

class Customer
{
public $custId;
public $custName;
function __construct()
{
$this->custId = 'Eazy01';
$this->custName = 'EazyLearnKaloor';
}

function DisplayDetails()
{
echo "$this->custId<br>"; // use $this here
echo "$this->custName"; // use $this here
}
}

$obj = new Customer();
$obj->DisplayDetails();

您还可以将变量传递给构造函数:

    function __construct($id, $name)
{
$this->custId = $id;
$this->custName = $name;
}

然后在初始化新类时你可以这样做:

$var = new Customer('Eeazy01', 'EazyLearnKaloor');

关于php - 使用构造函数初始化变量的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23117074/

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