简体   繁体   English

如何在另一个类中使用php类

[英]How to use a php class in another class

I searched for answers a lot, but only found stuff around questions of whether one can write a class in another class and stuff like that. 我搜索了很多答案,但只发现了关于是否可以在另一门课中一门课的问题,以及类似的问题。

So there is the first document, which is: 因此,第一个文档是:

Document1: 文档1:

class MyClass1 {

    private $myAttribute1;
    __construct(){
        this->myAttribute1 = 'blabla';
    }
}

now calling in the same document 现在调用同一文档

$myObject1 = new MyClass1();

works totally fine in NetBeans. 在NetBeans中完全可以正常工作。

Meanwhile when I build another document, lets call it Document2, and build another class there, which is intended to use MyClass1 , Netbeans tells me there is a problem: 同时,当我构建另一个文档时,将其命名为Document2,并在那里构建另一个类,该类旨在使用MyClass1 ,Netbeans告诉我存在一个问题:

Document2: 书2:

myClass2 {
    $myAttribute2 = new myClass1(); 
}

so this does not work in my NetBeans, just tells me 'unexpected new'. 因此这在我的NetBeans中不起作用,只是告诉我“意外的新消息”。 How can I use MyClass1 in myClass2 since this way does not work? 由于这种方式不起作用,如何在myClass2使用MyClass1

PHP only allows certain expressions to be used as initializer values for class attributes: PHP仅允许将某些表达式用作类属性的初始化器值:

class foo {
    $x = 7; //fine, constant value
    $y = 7+7; // only fine in recent PHPs
    $z = new bar(); // illegal in all PHP versions
}

The 7+7 version was only supported in recent PHP versions, and the ONLY expressions allowed are those whose resulting value can be COMPLETELY calculated at compile-time. 7+7版本仅在最新的PHP版本中受支持,并且仅允许使用那些表达式的结果值可以在编译时完全计算出的表达式。 Since the new cannot be executed at compile time, only at execution time, it's an outright permanently illegal expression. 由于new无法在编译时执行,只能在执行时执行,因此这是一个完全永久的非法表达。

That means for "complex" expressions, which can only be calculated at runtime, you have to do that expression in the constructor: 这意味着对于只能在运行时计算的“复杂”表达式,您必须在构造函数中执行该表达式:

class foo {
    public $z;
    function __construct(){ 
         $z = new bar();
    }
}

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

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