创建一个新的类对象并直接设置变量 - PHP

时间:2015-10-22 07:02:04

标签: php

我试图了解如何有效地创建新的类对象并直接设置变量。

我有一个班级:

class element_model
{
    public $sType;
    public $properties;
}

我有一个控制器,其中定义了以下功能:

public function create_element($sType, $properties)
{
    $oElement_model = new element_model($sType, $properties);
    return new element_model($sType, $properties);
}

但是这不会返回一个设置了属性的新element_model,它只返回一个空对象。 但是,它不会引发错误。

上述功能不起作用的原因是什么?

2 个答案:

答案 0 :(得分:1)

你必须传递给类的constructor,在PHP中你应该在类__construct中有一个方法:

class element_model
{
    public $sType;
    public $properties;

    public function __construct($type, $property)
    {
        $this->sType = $type;
        $this->properties = $property;
    }
}

然后你可以访问它们(注意变量是公共的)

$elem = new element_model($sType, $properties);
$elem->sType;

虽然在某些情况下封装vars更好(声明它们私有):

class element_model
{
    private $sType;
    private $properties;

    public function __construct($type, $property)
    {
        $this->sType = $type;
        $this->properties = $property;
    }

    public function getType()
    {
        return $this->sType;
    }

    public function getProperty()
    {
        return $this->properties;
    }
}

然后您可以通过 getter

访问变量
$elem = new element_model($sType, $properties);
$elem->getType(); //and
$elem->getProperty();

答案 1 :(得分:0)

您必须在类中创建一个__construct函数,该函数接受参数并设置变量。像这样:

class element_model{
    .
    .
    .
    public function __construct($type,$properties)
    {
        $this->sType = $type;
        $this->properties = $properties;
    }
}

创建对象时将调用__construct函数。

但是如果你想在编程中变得更加酷,只需将属性定义为私有,并创建getter和setter函数来访问对象的变量

private $sType;
public function getSType(){
   return $this->sType;
}
public function setSType($value){
    $this->sType = $value;
}
相关问题