简体   繁体   English

调用另一个函数内部的函数

[英]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 . 我想打电话从一个函数chooseProgram.php是在另一个函数内部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 致命错误:在第6行的C:\\ xampp \\ htdocs \\ testing \\ chooseProgram.php中,调用成员函数loadTitles()为null

arrayLoader.php arrayLoader.php

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

chooseProgram.php 选择程序.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. 我已经在Google上搜索了,但是我要么不明白发生了什么,要么我尝试了什么都不起作用。

Can anyone help? 有人可以帮忙吗? Thanks. 谢谢。

function loadTitles is dependent on arrayLoader so you should first call arrayLoader and then loadTitles . 函数loadTitles依赖于arrayLoader,因此您应该先调用arrayLoader,然后再调用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. 因为直到调用abc才定义xyz。

I don't know what is the point of having nested function but this can be done by changing parent function to a class: 我不知道具有嵌套函数的意义是什么,但是可以通过将父函数更改为类来实现:

arrayLoader.php arrayLoader.php

class arrayLoader {

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

chooseProgram.php 选择程序.php

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

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

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