2013-03-21 71 views
1

我有一個類和一些屬性和方法在類中的文件。在另一個php文件中訪問屬性和類的方法

我需要從另一個php文件訪問該類的屬性和方法。我想包括與類的文件,但它不是一個正確的方式,這種情況,因爲該文件包含一些回聲,它會生成HTML,如果我包含該文件將生成這些HTML在orher文件,我不dont想要,我只想訪問舊的屬性和方法。

+0

你可以張貼一些代碼? – 2013-03-21 22:10:19

+0

將函數移至第三個文件,然後將其包含在兩者中。 – 2013-03-21 22:10:53

+0

爲什麼不把你的課程分成自己的文件? – 2013-03-21 22:11:53

回答

0

所以,你的類有一個構造函數。刪除類的構造函數,並將類文件包含到頁面中。實例化您的對象並調用您需要的屬性或方法。

$object->property; 
$object->method(); 
+0

爲什麼應該將constrctor刪除?你爲什麼決定問題出在構造函數中? – 2013-03-21 22:17:09

+0

這不是問題。他說這個對象會生成html。因此,我認爲他實例化了這個對象。他當然也可以使用'Object :: method()' – u54r 2013-03-21 22:20:32

+0

他說「文件包含echo,它會生成html」,而不是該對象生成html。聽起來更像是在文件中,類定義也在課堂外有'echo' blah「;」。 – 2013-03-21 22:27:37

1

正如其他人所說,在他們自己的文件中定義類只不過是包含該類的一個更好的主意。

someClass.php

<?php 
class SomeClass{ 
    public __Construct(){ 
     echo "This is some class"; 
    } 
} 

的其他頁面上,你只包括和實例化類。

<?php 
include('someClass.php'); 
//do something 

但是,如果由於某種原因,你不能與類修改頁面,則可以使用輸出緩衝來的頁面沒有輸出。

<?php 
//start a buffer 
ob_start(); 
//include the page with class and html output. 
include("PageWithClassAndHTMLOutput.php"); 
//end the buffer and discard any output 
ob_end_clean(); 

$cls = new ClassFromIncludedPage(); 
$cls->someMethod(); 

這並不理想,因爲你會設置/覆蓋在包括頁面定義的任何變量,分析整個頁面,這樣做,它的任何處理。我已經使用這種方法(不是用於類,而是用於相同的想法)來執行諸如捕獲包含頁面的內容,並在它已經寫入屏幕上顯示時發送電子郵件。

0

我將使用一個房地產web應用程序的例子。例如,如果你想在其他類不是屬性類(即希望得到由物業編號屬性名稱合同類)的屬性名稱 - 基於Laravel 5.3 PHP框架

<?php namespace App\Http\Controllers\Operations; 
## THIS CONTROLLER - that wants to access content from another (adjacent) controller 

use App\Http\Controllers\Operations\PropertiesController; 

     Class ContractsController extends Controller{ 
      public function GetContractDetails() # a local method calling a method accessing other method from another class 
      { 
       $property_id = 13; 
       $data['property_name'] = (new PropertiesController)->GetPropertyName($property_id); 
       return response()->json($data, 200); 
      } 
     } 


<?php namespace App\Http\Controllers\Operations; 
# OTHER CONTROLLER - that is accessed by a controller in need 

Class PropertiesController extends Controller { 
    Class PropertiesController extends Controller{ 
     public function GetPropertyName($property_id) #method called by an adjacent class 
     { 
      return $property_name = 'D2/101/ROOM - 201'; 
     } 
    } 
} 
相關問題