简体   繁体   English

PHP /从不同文件的类调用函数

[英]PHP / calling a function from a class from a different file

I have to write two php files. 我必须写两个php文件。 The first one has to hold the main class with the functions and the second one should just call the function from the first file (main.php). 第一个必须包含具有函数的主类,第二个应仅从第一个文件(main.php)调用该函数。

main.php
<?php
class main {
    public function parseCSV(....

parse.php
<?php
include('main.php');
echo"<pre>";
print_r(parseCSV());
echo"</pre>";

If I put the function and the echo in one file, it works perfectly. 如果我将函数和回声放在一个文件中,它会完美地工作。 Hopefully you will understand my question and maybe you can give me a hint. 希望您能理解我的问题,也许您可​​以给我提示。

You don't have initiated the object and that's not even how you call methods/functions from the object... 您尚未启动对象,甚至也不是从对象调用方法/函数的方式...

Try this! 尝试这个! Parse.php Parse.php

<?php
include("main.php");

$object = new main();

echo "<pre">;
print_r($object->parseCSV());
echo "</pre>";
?>

You defined a class in the main.php file, so if you want to use the method of this class you'll have to instantiate it. 您在main.php文件中定义了一个类,因此,如果要使用此类的方法,则必须实例化它。 Something like this should work: 这样的事情应该起作用:

parse.php
<?php 
include_once('main.php');
$m=new main();
echo"<pre>";
print_r($m->parseCSV());
echo"</pre>";

Another possibility would be to declare the method as static. 另一种可能性是将方法声明为静态。 So the file main.php would become: 因此,文件main.php将变为:

<?php
class main {
    public static function parseCSV(....

Then you should be able to call the method like this: 然后,您应该能够像这样调用方法:

parse.php
<?php 
include_once('main.php');
echo"<pre>";
print_r(main::parseCSV());
echo"</pre> ...

Hope this is usefull... 希望这是有用的...

Sorry I was answering while somebody else posted his answer. 对不起,我正在回答,而其他人则发布了他的答案。 So I add just this. 所以我只添加这个。 Another possibility would be to declare the method as static. 另一种可能性是将方法声明为静态。 So the file main.php would become: 因此,文件main.php将变为:

<?php
class main {
    public static function parseCSV(....

Then you should be able to call the method like this: 然后,您应该能够像这样调用方法:

parse.php
<?php 
    include_once('main.php');
    echo"<pre>";
    print_r(main::parseCSV());
    echo"</pre> ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM