声明的全局变量在功能里面没有改变
问题描述:
我看过几个类似的代码段on at the PHP documentation site,但这个例子只是拒绝工作。声明的全局变量在功能里面没有改变
$catalog = 0; // initialize variable outside of function scope
function catalog_init()
{
global $catalog;
if (!file_exists ("cd_catalog.xml")){
$xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><catalog></catalog>";
$catalog = new SimpleXMLElement($xmlString);
$catalog->asXML('cd_catalog.xml');
} else
$catalog = simplexml_load_file("cd_catalog.xml");
}
catalog_init(); // should initialize $catalog, but doesn't.
调用catalog_init()后,$目录仍然是0。我知道的全局变量时一般不赞成,但是这是一个小作业。任何人都可以找出为什么这不起作用?
答
$catalogue = 0;
$catalogue = catalogue_init($catalogue);
function catalogue_init($catalogue) {
//your function content
return $catalogue;
}
你的函数什么都不返回。通过$目录作为参数,并删除全球$目录
什么是'catalog_init($目录)错误; ' – 2015-11-01 20:44:39
我知道这会起作用,但这有点避免了这个问题,不是吗?我想知道*为什么这不起作用。 – Steven
对不起,我只是不在乎为什么不应该使用的代码不工作。 – 2015-11-01 20:52:52