2012-10-18 33 views
2

這是一個非常基本的PHP問題:假設我有3個文件file1,file2,file3。如何在不同的PHP文件中使用實例化的對象

在file1中,我聲明瞭一個名爲Object的類。在文件2,我有一個實例化對象的方法,稱之爲$對象,調用此方法方法

file2中,這種方法看起來像

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

} 

最後,文件中的3我聲明另一個AnotherObject。所以,如果我在file3中有一個方法'method',我可以直接引用$ object的屬性,還是可以訪問ony的靜態方法?

+1

這也不是很基本的,面向對象不應該這樣 – JvdBerg

+0

@JvdBerg進行編程,我已經編輯我的職務,因此可以更清晰 – user1611830

+1

邊注:這不要緊,你是否有在不同的文件或不類 - 文件不是範圍/可見性邊界。 – VolkerK

回答

10

這不是多麼體面的OOp應該編程。爲每個課程分配自己的文件。據我瞭解,你有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); 
1

$object範圍有限制爲當然該方法。文件3是從該方法調用的,所以如果使用include(),我會認爲是。然而,從方法內部使用require_once(),使我問其他問題有關file3無法利用所示方法中的變量的優勢,如果它以前包含在其他地方,因此不包括在方法內。

相關問題