drcomwc134525 2011-10-19 09:36
浏览 33
已采纳

在类的构造函数中从另一个创建对象

I wanna make object from another class in other one. so I done it:

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

the national code will work correctly,but the Temp class will not work,where is the problem?

  • 写回答

2条回答 默认 最新

  • duanmu6752 2011-10-19 09:51
    关注

    Don`t forget to use " $this-> " when accessing class members, updated code=>

    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();
            ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?