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

But*_*kus 3 php

我尝试了这个,当我尝试在类"second"中实例化类"first"时出现错误.

类"second"中的注释部分会导致错误.

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;
    //}
}
Run Code Online (Sandbox Code Playgroud)

编辑:

这导致服务器错误,即使我在类"second"中的所有内容都是类"first"的实例化.

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

bus*_*les 9

试试这个:

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();
Run Code Online (Sandbox Code Playgroud)


ani*_*son 7

$fst = new first();
Run Code Online (Sandbox Code Playgroud)

您不能声明在函数外部实例化新类的变量.默认值不能是变量.它必须是字符串,数字或可能是数组.物品是被禁止的.

public showfirst() {
Run Code Online (Sandbox Code Playgroud)

function在那里忘记了这个词.

    $firsta = $this->first->a;
Run Code Online (Sandbox Code Playgroud)

您没有$first声明类变量.你把它命名$fst,并参考它$this->fst.

    echo "Here is first \$a: " . $firsta;
}
Run Code Online (Sandbox Code Playgroud)

为了您的目的(无论那些):

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