簡體   English   中英

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

[英]access property and method of a class in another php file

我有一個帶有類的文件,該類中有一些屬性和方法。

我需要從另一個php文件訪問該類的屬性和方法。 我想將文件包含在類中,但是對於這種情況,這不是正確的方法,因為該文件包含一些回顯,會生成html,如果我包含該文件,則會在我不知道的其他文件中生成這些html想要,我只想訪問舊的屬性和方法。

正如其他人所說,最好在自己的文件中定義類,但只包含該類並包含該類。

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();

這是不理想的,因為您將設置/覆蓋包含頁面中定義的任何變量,解析整個頁面並進行任何處理。 我已經使用此方法(不是用於類,而是相同的想法)來進行諸如捕獲包含的頁面並在已經將其寫成顯示在屏幕上時通過電子郵件發送的內容。

因此,您的類具有構造函數。 刪除類的構造函數,並將類文件包含在頁面中。 實例化對象並調用所需的屬性或方法。

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

我將使用房地產網絡應用程序中的示例。 例如,如果您想在屬性類之外的其他類中獲取屬性名(一個合同類,希望通過屬性ID獲得屬性名)-基於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';
        } 
    }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM