简体   繁体   中英

Calling a function that is inside another function

I have following files:

  1. arrayLoader.php
  2. chooseProgram.php

I want to call a function from chooseProgram.php that is inside another function in arrayLoader.php .

Here's the error message I'm getting:

Fatal error: Call to a member function loadTitles() on null in C:\\xampp\\htdocs\\testing\\chooseProgram.php on line 6

arrayLoader.php

function arrayLoader() {
    $arrayLoad = (file_get_contents("../files/TEMP_Array"));
    function loadTitles() {
        return $arrayLoad;
    }
    return;
}

chooseProgram.php

require('../tools/arrayLoader.php');
print "<pre>";
print_r(arrayLoader()->loadTitles());
print "</pre>";

I've googled, but I either don't understand what's going on, or what I've tried doesn't work.

Can anyone help? Thanks.

function loadTitles is dependent on arrayLoader so you should first call arrayLoader and then loadTitles .

ie. It will work.

    <?php
    abc();
    xyz();
       function abc(){
        echo "abc";
        function xyz(){
            echo "xyz";
        }
       }
    ?>

and it will not work

    <?php
    xyz();
       function abc(){
        echo "abc";
        function xyz(){
            echo "xyz";
        }
       }
    ?>

because xyz is not defined untill abc is not called.

I don't know what is the point of having nested function but this can be done by changing parent function to a class:

class arrayLoader {

   function loadTitles() {
       $arrayLoad = (file_get_contents("../files/TEMP_Array"));
       return $arrayLoad;
   }
}

require('../tools/arrayLoader.php');
$obj=new arrayLoader;
$result=$obj->loadTitles();
print "<pre>";
print_r($result);
print "</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