创建新的类对象并直接设置变量-PHP
我试图理解如何高效地创建一个新的类对象并直接设置变量 我有一门课:创建新的类对象并直接设置变量-PHP,php,Php,我试图理解如何高效地创建一个新的类对象并直接设置变量 我有一门课: class element_model { public $sType; public $properties; } 我有一个控制器,其中定义了以下功能: public function create_element($sType, $properties) { $oElement_model = new element_model($sType, $properties); return ne
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);
}
但这不会返回一个属性设置为的新元素_模型,它只返回一个空对象。
但是,它不会抛出错误
上面的函数不起作用的原因是什么?您必须传递给类的,在PHP中,您应该在类的\u构造中有一个方法:
class element_model
{
public $sType;
public $properties;
public function __construct($type, $property)
{
$this->sType = $type;
$this->properties = $property;
}
}
然后您可以访问它们(注意变量是公共的)
尽管在某些情况下,封装变量(声明它们为私有的)更好:
然后可以通过getter访问变量
$elem = new element_model($sType, $properties);
$elem->getType(); //and
$elem->getProperty();
必须在类中创建一个_构造函数,该函数接受参数并设置变量。像这样:
class element_model{
.
.
.
public function __construct($type,$properties)
{
$this->sType = $type;
$this->properties = $properties;
}
}
创建对象时将调用_construct函数
但是,如果您想在编程中表现得更酷,只需将属性定义为private,并创建getter和setter函数来访问对象的变量
private $sType;
public function getSType(){
return $this->sType;
}
public function setSType($value){
$this->sType = $value;
}
“如果你想在编程方面变得格外酷”–wut?像你这样天真的二传手是多余的,非常不酷。我想详细说明一下二传手/接球手在哪些情况下是有用的。@deceze,你能告诉我你为什么这么想吗?
class element_model{
.
.
.
public function __construct($type,$properties)
{
$this->sType = $type;
$this->properties = $properties;
}
}
private $sType;
public function getSType(){
return $this->sType;
}
public function setSType($value){
$this->sType = $value;
}