PHP将类的实例传递给另一个类 [英] PHP Passing an instance of a class to another class

查看:208
本文介绍了PHP将类的实例传递给另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是一个新的PHP OO编程技术,我有一个非常简单的广泛的问题,一般不好的做法是在类中实例化一个类然后将该实例传递给另一个类?

I'm still kind of new to PHP OO programming techniques and I have a very simple broad question, is it generally bad practice to instantiate a class in a class then pass that instance to another class?

我想要的是能够创建一个特定类的实例,我知道我将永远需要通过每个用户请求。第二类比任何只是一个帮助类更好,理想情况下在我的应用程序中它将是加载视图的加载器。

What I want is to be able to create an instance of a specific class I know I will always need through each user request. Class two is more than anything just a helper class, ideally in my application it would be a "loader" that loads the views.

第一个类调用其他两个类:

First class which calls the other two classes:

require 'classTwo.php';
require 'classThree.php';

class first {
     public $classTwo, $classThree;

     public function __construct() {
          $this -> classTwo = new classTwo;
          $this -> classThree = new classThree;

          $this -> classThree -> displayNum( $this -> classTwo );

     }
}

第二个类是帮助类:

class classTwo {
     public function returnVal() {
          return 123;
     }
}

第三类是action类,显示会发生:

Third class is the action class where actual work and final display would happen:

class classThree {
     public function displayNum( $instance ) {
          echo $instance -> returnVal();
     }
}

总的来说,我只想知道这是否是不好的做法

Overall I just want to know if this is bad practice because I never seen it done before.

推荐答案

这是一个好的习惯,注入任何依赖类,因为这允许你在单元测试期间很容易模拟。

It is good practice to inject any dependent classes, as this allows you to mock quite easily during unit testing.

一般来说,如果你有 ClassA ,它依赖于 ClassB 的一个实例,然后你可以做一些类似的操作。

Generally speaking, if you have ClassA and it relies on an instance of ClassB to function then you could do something like..

$objectB = new ClassB();
$objectA = new ClassA($objectB);

查看 http://net.tutsplus.com/tutorials/php/dependency-injection-in-php/

EDIT:构造函数注入将依赖项传递到新对象的构造函数中(如上所示)。

Constructor injection is passing the dependency into the new object's constructor (as demonstrated above).

Setter注入正在使用一个方法依赖关系,通常在依赖关键字不重要时使用:

Setter injection is using a method to set the dependency, and is usually utilised when the dependency isn't critical:

$objectB = new ClassB();
$objectA = new ClassA();
$objectA->setObjectB($objectB);

这篇关于PHP将类的实例传递给另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆