I have set an array in my config file that I use global in my functions.
This works fine, but now I want to pass the name of this array as a #param in my function.
// in config file:
$album_type_arr = array("appartamento", "villa");
global $album_type_arr; // pull in from db_config
echo $album_type_arr[0];
function buildmenu($name) {
$test = global $name . "_arr";
echo $test[0];
}
buildmenu("album_type");
You're looking for variable variables:
http://www.php.net/manual/en/language.variables.variable.php
function buildmenu($name) {
$test = $name . "_arr";
global ${$test};
echo ${$test}[0];
}
You can use "variable variables". This works:
function buildmenu($name) {
global ${$name. '_arr'};
$test = ${$name. '_arr'};
echo $test[0];
}
Related
Is there a way to access a member of an object, by using its name as a string?
When I declare an array...
$array = array();
$array['description_en']="hello";
$array['description_fr']="bonjour";
then I access a member like this:
$lang="en"; //just to show my purpose. it will be dynamic
$description = $array['description_'.$lang];
Can I do the same thing for objects?
For example:
$obj->description_en="hello";
$obj->description_fr="bonjour";
How can I access $obj->description_.$lang ?
class test
{
public $description_en = 'english';
}
$obj = new test();
$lang = 'en';
echo $obj->{"description_".$lang}; // echo's "english"
You can see more examples of variable variables here.
You can use this syntax:
<?php
class MyClass {
public $varA = 11;
public $varB = 22;
public $varC = 33;
}
$myObj = new MyClass();
echo $myObj->{"varA"} . "<br>";
echo $myObj->{"varB"} . "<br>";
echo $myObj->{"varC"} . "<br>";
This way, you can access object variables as if they were entries in an associative array.
Let's say I have this:
function data() {
$out['a'] = "abc";
$out['b'] = "def";
$out['c'] = "ghi";
return $out;
}
I can output the data by declaring it as a variable, then using the array index to echo it:
$data = data();
echo $data['a'];
echo $data['b'];
echo $data['c'];
But, I'm calling functions inline with other functions, and I'm trying to avoid having to declare a variable first. For instance, I want to do something like this:
echo data()[0]; //pulls first value in array without declaring it as a variable first. This needs to be variable i.e. data()[1] data()[2] etc.
Or more specifically, I'm actually trying to do it as a class:
$traverseXML->getData("Route", "incoming", "field", "value")[0]
//getData() returns an array, I'm trying to get a single value.
Personally i would do something like this
<?php
function data($key = false, $default = 'not found') {
$out['a'] = "abc";
$out['b'] = "def";
$out['c'] = "ghi";
if($key)
{
if(isset($out[$key]))
return $out[$key];
else
return $default;
}
else
return 'empty';
}
?>
<?= data('a') ?>
Here is how I set my Array:
$Post_Cat_Array = array();
while($row = mysql_fetch_array( $result )) {
$Post_Cat_Array[$row['type_id']] = $row['type_name'];}
in this function I need to get the type_id(key) of a specific type_name(value)
function NameToID($input){
echo array_search($input, $Post_Cat_Array);
}
and I call the function like this :
NameToID($_POST['type']);
But it's not working. It doesn't echo anything. I am sure the $_POST['type'] contains correct value.
note:value of $_POST['type'] is in arabic. same with all values of the array.
It seems that $Post_Cat_Array is out of scope. Modify your function:
function NameToID($input, $arr){
echo array_search($input, $arr);
}
and then:
NameToID($_POST['type'], $Post_Cat_Array);
From PHP Variable scope:
This script will not produce any output because the echo statement
refers to a local version of the (...) variable, and it has not been
assigned a value within this scope.
That is because your array variable is not known to your function. You can use either of the following to achieve that
<?php
$Post_Cat_Array=array();
$Post_Cat_Array["key1"]="value1";
$Post_Cat_Array["key2"]="value2";
$Post_Cat_Array["key3"]="value3";
$Post_Cat_Array["key4"]="value4";
echo NameToID("value4");
echo "<br>";
echo NameToID2("value4",$Post_Cat_Array);
function NameToID($input){
global $Post_Cat_Array;
echo array_search($input, $Post_Cat_Array);
}
function NameToID2($input,$values){
echo array_search($input, $values);
}
?>
I'm having some issues with the StdClass() object in PHP..
I'm using it to send information (a string and boolean) to a function.
Outside the function, it works great.
$args = new StdClass();
$args->str = "hej";
$args->ic = TRUE;
fun($arg);
This is then the function called:
function fun($args) {
$str = $args->str;
$ignore_case = $args->ic;
echo $str;
echo $ignore_case;
}
which just writes "stric" instead of the variable contents.
Is there a way to use StdClass to transfer this data and read it correctly?
//Martin
function fun($args) {
$str = $args->str;
$ignore_case = $args->ic;
echo $str;
echo $ignore_case;
}
add $ and second echo should be $ignore_case - I believe
$args = new StdClass();
$args->str = "hej";
$args->ic = TRUE;
fun($arg);
Where is $arg defined? Your call should be fun($args).
You forgot the $ before the variable names in your echos.
echo $str;
echo $ignore_case;
Also, fun($arg); should be fun($args);
My goal is to echo the argument passed to a function. For example, how can this be done?
$contact_name = 'foo';
function do_something($some_argument){
// echo 'contact_name' .... How???
}
do_something($contact_name);
You can't. If you want to do that, you need to pass the names as well, e.g:
$contact_name = 'foo';
$contact_phone = '555-1234';
function do_something($args = array()) {
foreach ($args as $name => $value) {
echo "$name: $value<br />";
}
}
do_something(compact('contact_name', 'contact_phone'));
Straight off the PHP.net variables page:
<?php
function vname(&$var, $scope=false, $prefix='unique', $suffix='value')
{
if($scope) $vals = $scope;
else $vals = $GLOBALS;
$old = $var;
$var = $new = $prefix.rand().$suffix;
$vname = FALSE;
foreach($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
?>
Not possible.
Variables are just means to address values or areas in the memory. You cannot get the variable name that’s value has been passed to a function.
Disclaimer: this will oonly work if you pass a variable to the function, not a value, and it only works when your not in a function or a class. So only the GLOBAL scope works :)
Good funct($var)
Bad funct(1)
You can do it actually contrary to popular believe ^_^. but it involves a few lookup tricks with the $GLOBALS variable.
you do it like so:
$variable_name = "some value, better if its unique";
function funct($var) {
foreach ($GLOBALS as $name => $value) {
if ($value == $var) {
echo $name; // will echo variable_name
break;
}
}
}
this method is not fool proof tho. Because if two variables have the same value, the function will get the name of the first one it finds. Not the one you want :P
Its best to make the variable value unique before hand if you want accuracy on variable names
Another method would be to use reference to be accurate like so
$variable_name = 123;
function funct(&$var) {
$old = $var;
$var = $checksum = md5(time()); // give it unique value
foreach ($GLOBALS as $name => $value) {
if ($value == $var) {
echo $name; // will echo variable_name
$var = $old; // reassign old value
break;
}
}
}
so it is entirely possible :)
Based on PTBNL's (most definately correct) answer i came up with a more readable (at least i think so) approach:
/**
* returns the name of the variable posted as the first parameter.
* If not called from global scope, pass in get_defined_vars() as the second parameter
*
* behind the scenes:
*
* this function only works because we are passing the first argument by reference.
* 1. we store the old value in a known variable
* 2. we overwrite the argument with a known randomized hash value
* 3. we loop through the scope's symbol table until we find the known value
* 4. we restore the arguments original value and
* 5. we return the name of the symbol we found in the table
*/
function variable_name( & $var, array $scope = null )
{
if ( $scope == null )
{
$scope = $GLOBALS;
}
$__variable_name_original_value = $var;
$__variable_name_temporary_value = md5( number_format( microtime( true ), 10, '', '' ).rand() );
$var = $__variable_name_temporary_value;
foreach( $scope as $variable => $value )
{
if ( $value == $__variable_name_temporary_value && $variable != '__variable_name_original_value' )
{
$var = $__variable_name_original_value;
return $variable;
}
}
return null;
}
// prove that it works:
$test = 1;
$hello = 1;
$world = 2;
$foo = 100;
$bar = 10;
$awesome = 1;
function test_from_local_scope()
{
$local_test = 1;
$local_hello = 1;
$local_world = 2;
$local_foo = 100;
$local_bar = 10;
$local_awesome = 1;
return variable_name( $local_awesome, get_defined_vars() );
}
printf( "%s\n", variable_name( $awesome, get_defined_vars() ) ); // will echo 'awesome'
printf( "%s\n", test_from_local_scope() ); // will also echo awesome;
Sander has the right answer, but here is the exact thing I was looking for:
$contact_name = 'foo';
function do_something($args = array(), $another_arg) {
foreach ($args as $name => $value) {
echo $name;
echo '<br>'.$another_arg;
}
}
do_something(compact(contact_name),'bar');
class Someone{
protected $name='';
public function __construct($name){
$this->name=$name;
}
public function doSomthing($arg){
echo "My name is: {$this->name} and I do {$arg}";
}
}
//in main
$Me=new Someone('Itay Moav');
$Me->doSomething('test');