我可以在另一个类中实例化一个 PHP 类吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1583140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:10:53  来源:igfitidea点击:

Can I instantiate a PHP class inside another class?

phpclassoopobject

提问by Richard

I was wondering if it is allowed to create an instance of a class inside another class.

我想知道是否允许在另一个类中创建一个类的实例。

Or, do I have to create it outside and then pass it in through the constructor? But then I would have created it without knowing if I would need it.

或者,我是否必须在外部创建它然后通过构造函数传入它?但后来我会在不知道我是否需要它的情况下创建它。

Example (a database class):

示例(一个数据库类):

class some{

if(.....){
include SITE_ROOT . 'applicatie/' . 'db.class.php';
$db=new db

采纳答案by Luká? Lalinsky

You can't define a class in another class. You should include files with other classes outside of the class. In your case, that will give you two top-level classes dband some. Now in the constructor of someyou can decide to create an instance of db. For example:

您不能在另一个类中定义一个类。您应该在类之外包含其他类的文件。在您的情况下,这将为您提供两个顶级类dbsome. 现在在构造函数中,some您可以决定创建db. 例如:

include SITE_ROOT . 'applicatie/' . 'db.class.php';

class some {

    public function __construct() {
        if (...) {
            $this->db = new db;
        }
    }

}

回答by vincentDV

People saying that it is possible to 'create a class within a class' seem to mean that it is possible to create an object / instance within a class. I have not seen an example of an actual class definition within another class definition, which would look like:

人们说可以“在类中创建类”似乎意味着可以在类中创建对象/实例。我还没有在另一个类定义中看到实际类定义的例子,它看起来像:

class myClass{

    class myNestedClass{

    }

}

/* THIS IS NOT ALLOWED AND SO IT WON'T WORK */

Since the question was 'is it possible to createa class insideanother class', I can now only assume that it is NOT possible.

由于问题是“是否可以另一个类中创建一个类”,我现在只能假设这是不可能的。

回答by rickchristie

I just wanted to point out that it is possible to load a class definition dynamically inside another class definition.

我只是想指出,可以在另一个类定义中动态加载一个类定义。

Lukas is right that we cannot define a class inside another class, but we can include() or require() them dynamically, since every functions and classes defined in the included file will have a global scope. If you need to load a class or function dynamically, simply include the files in one of the class' functions. You can do this:

Lukas 是对的,我们不能在另一个类中定义一个类,但我们可以动态地 include() 或 require() 它们,因为在包含文件中定义的每个函数和类都将具有全局作用域。如果您需要动态加载类或函数,只需将文件包含在类的函数之一中。你可以这样做:

function some()
{
    require('db.php');
    $db = new Db();
    ...
}

http://php.net/manual/en/function.include.php

http://php.net/manual/en/function.include.php

回答by Marius Burz

It's impossible to create a class in another class in PHP. Creating an object(an instance of a class) in another object is a different thing.

在 PHP 中的另一个类中创建一个类是不可能的。在另一个对象中创建对象(类的实例)是另一回事。

回答by Radek M

No, it is not possible. Nesting classes and aggregating objects are diffrent mechanisms. Nesting classes means nesting class names, in fact. Class A nested in class B would be named "B\A" (?). From v5.3 you can nest class names (and some other names) in namespaces.

不,这是不可能的。嵌套类和聚合对象是不同的机制。事实上,嵌套类意味着嵌套类名。嵌套在 B 类中的 A 类将被命名为“B\A”(?)。从 v5.3 开始,您可以在命名空间中嵌套类名(和一些其他名称)。

回答by Jon Surrell

This is possible in PHP 7 with Anonymous classes.

这在带有匿名类的PHP 7 中是可能的。

See the example from the docs:

请参阅文档中的示例:

class Outer
{
    private $prop = 1;
    protected $prop2 = 2;

    protected function func1()
    {
        return 3;
    }

    public function func2()
    {
        return new class($this->prop) extends Outer {
            private $prop3;

            public function __construct($prop)
            {
                $this->prop3 = $prop;
            }

            public function func3()
            {
                return $this->prop2 + $this->prop3 + $this->func1();
            }
        };
    }
}

echo (new Outer)->func2()->func3();
// Output: 6

This is a simple example showing usage of anonymous classes, but not from within a class:

这是一个简单的例子,展示了匿名类的用法,但不是在类中:

// Pre PHP 7 code
class Logger
{
    public function log($msg)
    {
        echo $msg;
    }
}

$util->setLogger(new Logger());

// PHP 7+ code
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});

回答by Siegfried DuDragon

(Edit) Ok the question and the example of what you are trying to accomplish are confusing. It seems from your example you are trying to DEFINE a class inside another class.

(编辑)好的,您要完成的问题和示例令人困惑。从您的示例看来,您正试图在另一个类中定义一个类。

The correct name for this is NESTED CLASS and it is not possible in PHP. So, to your example the answer is "NO". Not in PHP anyway. Other languages will allow "nested classes". Javais an example.

正确的名称是 NESTED CLASS,在 PHP 中是不可能的。因此,对于您的示例,答案是“否”。反正不是在 PHP 中。其他语言将允许“嵌套类”。Java就是一个例子。

For example this will NOT work in PHP

例如,这在 PHP 中不起作用

class outer_class{
    class inner_class{
        ...
    }
    ...
}

Now the question asked is to create AN INSTANCE of a class in another class.

现在提出的问题是在另一个类中创建一个类的实例。

To this the answer is "YES", you can INSTANTIATE an "object" inside a "class". We do it all the time.

对此,答案是“是”,您可以在“类”中实例化“对象”。我们一直这样做。

class simple_class{

    protected $instanceOfOtherClass;

    public function instanciateObject_KeepingAReferenceToIt(){
        // create an instance of OtherClass and associate it to $this->instanceOfOtherClass
        $this->instanceOfOtherClass = new OtherClass();
    }

    public function instanciateObject_Without_KeepingAReferenceToIt(){
        // create an instance of OtherClass and return it
        return new OtherClass();
    }
}

A class can even instantiate itself. That's what the famous singleton does and many other Creational patterns. Sadly some people believe that knowing about dependency injectionmeans they will never call NEW in a method again. WRONG.

一个类甚至可以实例化自己。这就是著名的单身人士和许多其他创作模式所做的。可悲的是,有些人认为了解依赖注入意味着他们再也不会在方法中调用 NEW。错误的。

It helps to understand the difference between a class and an object. A classis an extensible program-code-template for creating objects. An objectrefers to a particular instance of a class.

它有助于理解类和对象之间的区别。一是可扩展的程序代码模板来创建对象。一个对象是指一类的特定实例。

回答by teymzz

I'm just seeing this now and I wish to add my comment. It could be of benefit to anyone. Has anyone heard of php traits? Although traits does not import another class but only imports a trait into another class. So instead of trying to import several classes, you can have a main classe while the subclasses will act like traits making it possible for you to use them in main/parent classes

我现在才看到这个,我想添加我的评论。它可能对任何人都有好处。有人听说过 php 特性吗?尽管traits 不会导入另一个类,而只是将一个trait 导入另一个类。因此,与其尝试导入多个类,您可以拥有一个主类,而子类将充当特征,使您可以在主/父类中使用它们