Error when including file within function

Asked

Viewed 41 times

1

Guys I’m putting together a system where I want to do it mutipla language... Well created the project, inside it has a folder strings (where inside has a file called EN-BR.php), has a file functions (where has a function that passes the file name and includes with include_once), in the file I’m doing the test while including and calling function it all normal, but when I echo a var that is inside the file, error. How can I solve ? or is there an easier way ? Thank you

php test file.

<?php
include_once ("class/funcoes.php");
autoLoad();
session_start();
$sl = $_SESSION['lang']; //Passa PT-BR
defineLanguage($sl);
echo $strNome;

class/funcoes.php file

<?php

    function defineLanguage ($language) {
        $dir = "strings/";
        if($language == "PT-BR") {
            $include = $dir . "PT-BR" . ".php";
            //include_once($include);
            include('strings/PT-BR.php');
        }
    }

string file/EN.php

<?php
$strNome = "teste";

ERROR

Notice: Undefined variable: strNome in /Applications/XAMPP/xamppfiles/htdocs/log-u/testeSession.php on line 11

  • You can resolve this by posting the code and error message.

  • @rray I put the code...

1 answer

1


The problem is that include is done inside the function, so all variables defined in it and include’s are restricted to function as nothing is returned occurs undefined variable.

Do it right, in your function return the path of the location file (you may need to define constants with the path of root and location directories), use the return as the include/require argument.

Function:

function defineLanguage ($language) {
    $dir = "strings/";
    if($language == "PT-BR") {
        return $dir . "PT-BR" . ".php";
    }
}

Calling for:

<?php
include_once ("class/funcoes.php");
autoLoad();
session_start();
$sl = $_SESSION['lang']; //Passa PT-BR
$arquivo = defineLanguage($sl);
require_once($arquivo); //<--- linha adicionada
echo $strNome;
  • worked... but there’s no way I can get this code to not replicate in all pgs ?

  • @Augustofurlan this part of the language definition you put in a separate file and make include/require it in the others or if you are doing the website Institutional, with fixed texts and few pages can upload everything in the session.

  • ok thanks @rray

Browser other questions tagged

You are not signed in. Login or sign up in order to post.