Php 在类的构造函数中从另一个生成对象
我想从另一个类中创建对象。 所以我做到了:Php 在类的构造函数中从另一个生成对象,php,oop,scope,Php,Oop,Scope,我想从另一个类中创建对象。 所以我做到了: class National_Number{ private $num = array(); public function __construct($first = NULL,$second = NULL,$third = NULL) { $this->set($first,0); $this->set($second,1); $this->set($third,2); }
class National_Number{
private $num = array();
public function __construct($first = NULL,$second = NULL,$third = NULL) {
$this->set($first,0);
$this->set($second,1);
$this->set($third,2);
}
public function set($num = NULL,$part = 0)
{
if ($num != NULL AND $part num[$part] = $num;
else
return FALSE;
}
else
{
return FALSE;
}
}
public function get($part = 0)
{
if ($part num[$part];
else
return FALSE;
}
}
class Temp {
private $ID;
public function __construct() {
$ID = new National_Number(127,110,8100);
}
public function _get()
{
var_dump($ID->get());
}
}
$temp = new Temp();
$temp->_get();
国家代码将正常工作,但Temp类将不工作,问题出在哪里?
$ID
是一个局部变量,仅在\u construct()中有效。如果要引用属性,必须使用$this->ID
$this->ID = new National_Number(127,110,8100);
同样适用于\uu get()
访问类成员时,不要忘记使用“$this->”,更新的代码=>
class National_Number{
private $num = array();
public function __construct($first = NULL,$second = NULL,$third = NULL) {
$this->set($first,0);
$this->set($second,1);
$this->set($third,2);
}
public function set($nume = NULL,$part = 0)
{
if ($nume != NULL AND $part){
$this->num[$part] = $nume;
}
else
return FALSE;
}
public function get($part = 0)
{
if (isset($this->num[$part])){
return $this->num[$part];
}
else
return FALSE;
}
}
class Temp {
private $ID;
public function __construct() {
$this->ID = new National_Number(127,110,8100);
}
public function _get()
{
var_dump($this->ID->get(1));
}
}
$temp = new Temp();
$temp->_get();
?>
试过$this->ID
了吗?这里的代码看起来像是坏代码:if($partnum[$part];
。ctrl+c有什么问题吗?