我们可以在 php 的另一个类中创建一个类的对象吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10634014/
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-24 22:40:28  来源:igfitidea点击:

Can we create an object of a class inside another class in php?

phpclassobject

提问by Maystar

Can we create an object of a class inside another class in php?I hav made a small application in php,now I am trying to convert the entire code in a class-methods-object fashion.I m now Confused.

我们可以在 php 的另一个类中创建一个类的对象吗?我在 php 中做了一个小应用程序,现在我试图以类-方法-对象的方式转换整个代码。我现在很困惑。

采纳答案by Samy Dindane

Yes you can, but that increases code coupling and makes testing harder.
I'd suggest creating it outside the class and pass it as an argument (it is called Dependency Injection).

是的,您可以,但这会增加代码耦合并使测试更加困难。
我建议在类之外创建它并将其作为参数传递(称为依赖注入)。

class Foo
{
}

class Bar
{
  public function __construct(Foo $foo)
  {
    $this->foo = $foo;
  }
}

$foo = new Foo();
$bar = new Bar($foo);

回答by Gordon

You you can do that, but whether you should depends on the lifetime of the two classes and their relation to each other. Basically, you have the choice between Compositionand Aggregation.

你可以这样做,但是否应该取决于两个类的生命周期以及它们之间的关系。基本上,您可以在CompositionAggregation之间进行选择。

Composition

作品

You use Composition when the created object has a lifetime equal or less than the object that will use it, e.g.

当创建的对象的生命周期等于或小于将使用它的对象时,您可以使用 Composition,例如

class A 
{
    private $belongsToAOnly;

    public function __construct()
    {
        $this->belongsToAOnly = new IBelongToA;
    }
}

In this case A"owns" IBelongToA. When Ais destroyed, IBelongToAis destroyed too. It cannot live on it's own and is likely just an implementation detail of A. It could be a ValueObjectlike Moneyor some other Data Type.

在这种情况下,A“拥有” IBelongToA。当A被破坏,IBelongToA太破坏。它不能独立存在,可能只是A. 这可能是一个的ValueObjectMoney或某种其他数据类型。

From Craig Larman's "Applying UML and Patterns":

来自 Craig Larman 的“应用 UML 和模式”:

the composite is responsible for creation and deletion of it's parts - either by itself creating/deleting the parts, or by collaborating with other objects. Related to this constraint is that if the composite is destroyed, its parts must be destroyed, or attached to another composite"

复合体负责创建和删除它的部分——或者通过它自己创建/删除部分,或者通过与其他对象协作。与此约束相关的是,如果复合材料被破坏,则其部件必须被破坏,或附加到另一个复合材料上”

Aggregation

聚合

You use Aggregation when the lifetime of the created object is longer:

当创建的对象的生命周期较长时,您可以使用聚合:

class A 
{
    private $dbAdapter;

    public function __construct(DbAdapter $dbAdapter)
    {
        $this->dbAdapter = $dbAdapter;
    }
}

Unlike with Composition, there is no implication of ownership here. Auses DbAdapterbut when Ais destroyed DBAdapterlives on. It's a "uses" relationship instead of an "owns" relationship.

与 Composition 不同,这里没有所有权的含义。A使用DbAdapter但当A被摧毁时仍然DBAdapter存在。这是一种“使用”关系,而不是“拥有”关系。

Creator Pattern (GRASP)

创作者模式 (GRASP)

A good heuristic to decide when an object may create another object at runtime can be found in the Creator Pattern in GRASPwhich states that objects may create other objects when

可以在 GRASP中的创建者模式中找到一个很好的启发式方法来决定一个对象何时可以在运行时创建另一个对象,该模式指出对象可以在以下情况下创建其他对象

  • Instances of B contains or compositely aggregates instances of A
  • Instances of B record instances of A
  • Instances of B closely use instances of A
  • Instances of B have the initializing information for instances of A and pass it on creation.
  • B 的实例包含或复合聚合 A 的实例
  • B 的实例记录 A 的实例
  • B 的实例密切使用 A 的实例
  • B 的实例具有 A 实例的初始化信息,并在创建时传递它。

Alternatively, you can create Factories whenever you need to create instances of something and aggregate the factory instances, which will give you a cleaner separation of collaborators and creators.

或者,您可以在需要创建某事物的实例并聚合工厂实例时创建工厂,这将使您更清晰地分离协作者和创建者

Testability

可测试性

An issue stemming from creating objects within objects is that they are difficult to test. When you do unit-testing, you usually do not want to recreate and bootstrap the entire system environment but concentrate on testing just that particular class in isolation. To do that, you swap out dependencies of that class with Mock Objects. You cannot do that when you use Composition.

在对象内创建对象的一个​​问题是它们难以测试。当您进行单元测试时,您通常不想重新创建和引导整个系统环境,而是专注于单独测试该特定类。为此,您可以使用Mock Objects替换该类的依赖项。当您使用 Composition 时,您不能这样做。

So depending on what the collaborators of a class do, you might want to decide to always use Aggregation, because then you are effectively doing Dependency Injectionall the way, which will allow you to swap out collaborators of a class easily, for instance to replace them with Mocks.

因此,根据类的协作者所做的事情,您可能希望决定始终使用聚合,因为这样您就可以一直有效地进行依赖注入,这将使您可以轻松地交换类的协作者,例如替换他们用 Mocks。

回答by Rukmi Patel

yes you can do it ..

是的,你可以做到..

here is one example..

这是一个例子..

a.php
<?php
    class a{
        public function function_1(){
           echo "b";
        }
     }
?>


b.php
<?php
     include_once ("a.php");
     class b{
        public function function_b(){
             $a = new a;
             $a->function_1();
        }
      }
      $b= new b;
      $b->function_b();
 ?>

回答by Jage

Yes, you can create an object from a specific class from inside another class.

是的,您可以从另一个类中的特定类创建对象。

class SomeClass{

}
class SomeOtherClass {
     function hello(){
         $o = new SomeClass;
     }
}

回答by Tufan Bar?? Y?ld?r?m

Yes, you can also define a function in a class. You can do everything in a class in php, please post your code where you confused.

是的,您也可以在类中定义函数。您可以在 php 的类中完成所有操作,请将您的代码发布到您感到困惑的地方。

Examples: Object in a class.

示例:类中的对象。

class Foo
{
   public $bar; // another object!

   public __construct()
   {
      $this->bar = new Bar();
    }
}

(global)Function in a class

(全局)类中的函数

<?php
    class Foo
    {
        public function __construct()
        {
            function __construct()
            {
                echo "Yes, I'm a global function!";
            }
        }
    }

    new Foo();
    __construct();

?>