开发者

array becamed nulled in the class

hay my开发者_C百科 class

class language{

    function merge($filename = ''){ 
// the path is true
    return include_once ('language/'.$filename);
    }

}

ok this lang test

en.php

<?php

if (empty($lang) || !is_array($lang))
{
    $lang = array();
}

$lang = array_merge($lang, array(
    'test'      => 'Home Page'

));

?>

if i add

echo $lang['test']; 

in the en.php its return Home Page

but i i make the class

$l = new language;
$l->merge('en.php');

its not working i checked it

var_dump($lang);

it return null


if you want to return something from an include_once call you have to return something in the file. See Example 5.

<?php // return.php
    $var = 'PHP';
    return $var;
?>

vs.

<?php // noreturn.php
     $var = 'PHP';
?>

gives

<?php
    $foo = include 'return.php';
    echo $foo; // prints 'PHP'

    $bar = include 'noreturn.php';
    echo $bar; // prints 1
 ?>


The $lang variables does not exist because you're including the en.php file at the scope of the merge function. From the PHP manual…

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Hence $lang is lost when merge returns, unless you declare it global in that function.


see my soultion

function __construct(){ 
$this->lang =  array();
}

class language{

    function merge($filename = ''){     
include_once ('language/'.$filename);

    return $this->lang = $lang;
    }

}

and when use echo $l->lang['test'];

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜