Global Not Working
I have a file in PHP with a large array and a function that searches the array.
Heres the code:
$details = array(
array('fieldID'=>'0','fieldCaption'=>'Address 1','fieldType'=>'text','fieldName'=>'addr1','fieldRequired'=>'1'),
array('fieldID'=>'1','fieldCaption'=>'Address 2','fieldType'=>'text','fieldName'=>'addr2','fieldRequired'=>'1'),
.
.
.
);
if(!function_exists('find_detail'))
{
function find_detail($fieldName)
{
global $details;
var_dump($details); // NULL
foreach ($details as $detail)
{
if($detail['fieldName'] == $fieldName)
{
return $detail['fieldID'];
}
}
return false;
}
}
This sits inside a single helper file and calling var_dump($details); is returning NULL. I suspect an issue with scoping.
Many Thanks
-- edit --
This is bad practice and the best approach to handling this would be (as @Gordon stated) to pass the details array into the function. (Warning: There exist better ways of doing this, for example using array_filter)
if(!function_exists('find_detail_by_field_name'))
{
function find_detail_by_field_name($details, $fieldName)
{
foreach ($details as $detail)
{
if($detail['fieldName'] == $fieldName)
{
return $detail['fieldID'];
}
}
return false;
}
}
And provide a way to get the details, wrapping details in a function would provide many benefits such as caching, change of source etc.
functio开发者_开发技巧n get_details()
{
static $details = array(...)
return $details;
}
The answer as to why global
seems to be not working is that CI's helper files are included into a function scope. In other words $details
array is not in global scope, so global
does not see it.
As to how you should do it instead - see other's answers.
If your function operates on that $details
array, it should ask for that array in the function signature. Anything else is just hiding dependencies and is hard to debug and maintain (as you can see by the need to ask your question). So change it to
function find_detail($fieldName, array $details)
and foreach over the passed in array then.
Also, since the function really returns the fieldId and not some detail, you might want to rename it to
function findFieldIdByFieldName($fieldName, array $details)
But to answer your question: you likely get this effect because you created the $details array outside the global scope, the topmost scope of your script. If you defined $details in a function or a method or if it is included in the scope of another function, it is not in the global scope.
In addition, you may consider to use Config class instead global
. In that way, you have a static array variable and whenever you need it, just call CI Config function using CI super object $ci =& get_instance();
in your helper.
精彩评论