简体   繁体   English

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

[英]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". 我尝试了这个,当我尝试在类“second”中实例化类“first”时出现错误。

The commented sections inside of class "second" cause errors. 类“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;
    //}
}

EDIT: 编辑:

This results in a server error even though all I have in class "second" is the instantiation of class "first". 这导致服务器错误,即使我在类“second”中的所有内容都是类“first”的实例化。

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

try this: 尝试这个:

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. 你忘记了那里的单词function

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

You have no class variable $first declared. 你没有$first声明的类变量$first You named it $fst and would reference it as $this->fst . 你将其命名为$fst 并将其引用为$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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM