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

时间:2014-04-16 18:14:31

标签: php oop

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

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

6 个答案:

答案 0 :(得分:2)

您需要使用__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');

答案 1 :(得分:2)

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

答案 2 :(得分:1)

您需要使用双下划线:__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();

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

在__construct()和$this中使用双下划线来回显&#39;回声&#39; DisplayDetails

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

答案 5 :(得分:0)

不是真正的&#34;正确&#34;方式,但这将工作得很好。通常,您将值传递给构造函数(注意双下划线):

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;
}
相关问题