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


Correct way of initialising the variables using constructor

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

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');

imho正确的方式是

class Customer
{
    public $custId;
    public $custName;
    // double underscores
    function __construct($custId = 'Eazy01', $custName = 'EazyLearnKallor')
    {
        $this->custId   = $custId;
        $this->custName = $custName;
    }
    function DisplayDetails()
    {
        echo $this->custId . '<br />' . $this->custName;
    }
}
$obj = new Customer();
$obj->DisplayDetails();

您需要使用双下划线:__construct,当您想要打印变量时,必须使用$this->propertyName。代码的其余部分是正确的。

class Customer
{
    public $custId;
    public $custName;
    function _construct($custId = '', $custName = '')
    {
        $this->custId   = $custId;
        $this->custName = $custName;
    }
    function DisplayDetails()
    {
        $content  = $this->custId . "<br />";
        $content .= $this->custName;
        echo $content;
    }
}
$obj = new Customer();
$obj->DisplayDetails();

如果使用这种编码方式,就不必将参数传递给构造函数。您可以使用:

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

$obj = new Customer('Hello', 'World');
$obj->DisplayDetails();

还有

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

是。。。但是PHP中的构造函数名为__construct()

此外,您应该为属性使用Getters和Setters,并使它们受到保护或私有

在__construct()和$this中使用双下划线在DisplayDetails 上"回显"参数

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

没有真正"正确"的方法,但它会很好地工作。通常,您将值传递给构造函数(注意双下划线):

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

然后:

$obj = new Customer('Eazy01', 'EazyLearnKaloor');

此外,当你提到它们时,你需要在它们前面加上$this:

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