繁体   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