【问题标题】:How to use an instantiated object across different PHP files如何在不同的 PHP 文件中使用实例化对象
【发布时间】:2012-10-18 23:13:35
【问题描述】:

这是一个非常基本的 php 问题:假设我有 3 个文件,file1、file2、file3。

在 file1 中,我声明了一个名为 Object 的类。在file2中,我有一个实例化Object的方法,叫它$object,调用这个方法Method

在file2中,这个方法看起来像

public function Method(){
$object = new Object;
...
require_once(file3);
$anotherobject = new AnotherObject;
$anotherobject->method();

}

最后,在文件 3 中,我声明了另一个 AnotherObject。那么,如果我在file3中有一个方法'method',我可以直接引用$object的属性,还是可以访问Object的静态方法?

【问题讨论】:

  • 这不是很基础,OOp不应该这样编程
  • @JvdBerg,我已经编辑了我的帖子,这样可以更清楚
  • 旁注:你是否在不同的文件中有类都没有关系 - 文件不是范围/可见性边界。

标签: php object instantiation


【解决方案1】:

这不是体面的面向对象编程方式。给每个班级自己的文件。据我了解,您有 3 个包含类的文件,并且想要使用实例化对象。使用依赖注入来构造相互依赖的类。

例子:

file1.php

class Object
{
   public function SomeMethod()
   {
      // do stuff
   }
}

file2.php,使用实例化对象:

class OtherObject
{
   private $object;

   public function __construct(Object $object)
   {
      $this->object = $object;
   }

   // now use any public method on object
   public AMethod()
   {
      $this->object->SomeMethod();
   }
}

file3.php,使用多个实例化对象:

class ComplexObject
{
   private $object;
   private $otherobject;

   public function __construct(Object $object, OtherObject $otherobject)
   {
      $this->object = $object;
      $this->otherobject = $otherobject;
   }
}

将所有这些放在一个引导文件或某种程序文件中:

program.php

// with no autoloader present:
include_once 'file1.php';
include_once 'file2.php';
include_once 'file3.php';

$object = new Object();
$otherobject = new OtherObject( $object );

$complexobject = new ComplexObject( $object, $otherobject );

【讨论】:

    【解决方案2】:

    $object 的范围当然限于方法。文件 3 是从方法中调用的,所以我认为是的,如果使用 include()。但是,从方法内部使用require_once(),让我提出其他问题,即如果 file3 先前包含在其他地方,因此不包含在方法中,则可能无法利用显示的方法中的变量。

    【讨论】:

      猜你喜欢
      • 2014-12-11
      • 1970-01-01
      • 2017-02-28
      • 2011-11-15
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多