2

这是一个非常基本的 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 中有一个方法“方法”,我可以直接引用 $object 的属性,还是可以只访问 Object 的静态方法?

4

2 回答 2

10

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

例子:

文件1.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;
   }
}

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

程序.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 );
于 2012-10-18T14:51:59.347 回答
1

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

于 2012-10-18T14:52:25.847 回答