简体   繁体   中英

PHP / calling a function from a class from a different file

I have to write two php files. 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
<?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

<?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. 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:

<?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:

<?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> ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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