Can a class instantiate another class? (PHP)

I tried this and I get an error when I try to instantiate class "first" inside of class "second".

The commented sections inside of class "second" cause errors.

class first {
    public $a;

    function __construct() {
        $this->a = 'a';
    }
}

class second {
    //$fst = new first();
    //public showfirst() {
        //$firsta = $this->first->a;
    //  echo "Here is first $a: " . $firsta;
    //}
}

EDIT:

This results in a server error even though all I have in class "second" is the instantiation of class "first".

class second {
    $fst = new first();
    //public showfirsta() {
    //  $firsta = $this->fst->a;
    //  echo "Here is first $a: " . $firsta;
    //}
}

尝试这个:

class First {
    public $a;

    public function __construct() {
        $this->a = 'a';
    }

    public function getA() {
      return $this->a;
    }
}

    class Second {
        protected $fst;
        public function __construct() {
          $this->fst = new First();
        }

        public function showfirst() {
           $firsta = $this->fst->getA();
           echo "Here is first {$firsta}";
        }
    }

    $test = new Second();
    $test->showfirst();

$fst = new first();

You cannot declare a variable that instantiates a new class outside of a function. The default value cannot be variable. It has to be a string, a number, or possibly an array. Objects are forbidden.

public showfirst() {

You forgot the word function in there.

    $firsta = $this->first->a;

You have no class variable $first declared. You named it $fst and would reference it as $this->fst .

    echo "Here is first $a: " . $firsta;
}

For your purposes (whatever those may be):

class second {
    public function showfirst() {
        $fst = new first();
        $firsta = $fst->a;
        echo "Here is first $a: " . $firsta;
    }
}

You can instantiate a class inside another. In your case, in your both example you keep referring to the wrong variable. Also, you can't assign a class in the declaration of a property:

class second {

    public $fst;

    public function showfirsta() {
    $this->fst = new first();
    $firsta = $this->fst->a;
    echo "Here is first $a: " . $firsta;
    }
}
链接地址: http://www.djcxy.com/p/59550.html

上一篇: 参考 - 这个符号在PHP中的含义是什么?

下一篇: 一个类可以实例化另一个类吗? (PHP)