0

i have anonymous function in php file like

translation.php

$translateString = function($msg) use ($data) {
    return $msg;
}

and i am including that translation.php in one of my class file like in base.php

<?php
include "translation.php"

Class base {

   public function translateString($msg) {
       return $translateString($msg);
   }
}

and i am calling that function via ajax.

like: GetData.php Calling ajax like: https://example.com/GetData.php

<?php
   session_start();
   header('Content-Type: application/json');
   include 'classes/Autoload.php';
   function getTest() {
       $test = new Base();
       return $test->d();
   }
   $request_clean = clean($_REQUEST);
   $response = call_user_func($request_clean['func'], $request_clean);
   echo json_encode($response);
?>

When i include Autoload.php file in GetData.php file at that time this error occurs.

if i include only Base.php than there is a no issue

Autoload.php

<?php
function ClassesAutoload($classname)
{
    //Can't use __DIR__ as it's only in PHP 5.3+
    $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.$classname.'.php';
    if (is_readable($filename)) {
        include $filename;
    }
}

if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
    //SPL autoloading was introduced in PHP 5.1.2
    if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
        spl_autoload_register('ClassesAutoload', true, true);
    } else {
        spl_autoload_register('ClassesAutoload');
    }
} else {
    function __autoload($classname)
    {
        ClassesAutoload($classname);
    }
}

in that case i am getting an error like:

Uncaught Error: Function name must be a string

i tried so many example for fix it which are given in SO and other websites.

like one of them is

public function translateString($msg) {
    return $translateString[$msg]; //replaced () to []
}

with above solution error is gone but parameter values are not passing in it.

Nirav Joshi
  • 2,924
  • 1
  • 23
  • 45
  • 1
    `$translateString` is not in scope in `function translateString`. You'll need a `global...` – Nick May 11 '19 at 07:59
  • 1
    Working demo https://3v4l.org/ZpGvE – Nick May 11 '19 at 08:02
  • If using a global isn't working then you must have a different issue. If you edit the question with the new information I can reopen. Or start a new question. – Nick May 11 '19 at 08:11
  • Ok it got solved by adding `global $translateString` before include file. thank you. – Nirav Joshi May 11 '19 at 11:01

0 Answers0