I have a function called check_nickname()
And I want to write something like this
$ttt='nickname';
check_.$ttt();
How can I do it correct ?
I would advise against that.
this will produce unmaintainable and undebuggable code.
I'd make one function which does all the verifications.
Create a variable that holds the function name, and apply parentheses to it:
$ttt='nickname';
$funcname = 'check_'.$ttt;
$funcname();
You would need to create another variable, such as $a = "check_".$ttt;, then call $a();
$ttt = 'nickname';
$your_function = 'check_' . $ttt;
$your_function();
Related
This is PHP 5.4 code...
<?php
function abc($YesNo){return $YesNo["value"];}
$YesNo = array("value"=>"No","text"=>"No");
$x = array("active"=>function(){return abc($YesNo);});
echo $x['active']();
?>
Notice: Undefined variable: YesNo on line 7
Output Should be : Yes
if i directly put array in code by replace $YesNo like
<?php
function abc($YesNo){return $YesNo["value"];}
$x = array("active"=>function(){return abc(array("value"=>"Yes","text"=>"Yes"));});
echo $x['active']();
?>
output : Yes
which is correct output. Now what's the problem in first code. I need that for re-usability
Try this,
You can use use for passing data to a closure.
<?php
function abc($YesNo){return $YesNo["value"];}
$YesNo = array("value"=>"No","text"=>"No");
$x = array("active"=>function() use ($YesNo) {return abc($YesNo);});
echo $x['active']();
?>
You provide your anonymous function with a parameter:
$x = array("active"=>function($param){return abc($param);});
then you call it:
echo $x['active']($YesNo);
You may use the use keyword to make your function aware of an external variable:
$x = array("active"=>function() use ($YesNo) {return abc($YesNo);});
but it would be quite against the idea of reusability, in this case.
The problem is that your variable is not accessible within the function due to Variable Scope.
Because the array is defined outside of the function, it is not by default available inside the function.
There's a couple of solutions
Disclaimer: These are intended to fit within the scope of the question. I understand that they are not necessarily best practice, which would require a larger discussion
First Option:
You can declare the array within the function, like below. This is useful if you don't need access to it outside of the function.
function abc($YesNo){
$YesNo = array("value"=>"No","text"=>"No");
return $YesNo["value"];
}
Second Option:
Within your abc function, you can add the line global $YesNo. This is useful if you do need access to the array outside of the function:
function abc($YesNo){
global $YesNo;
return $YesNo["value"];
}
Other options exist (such as moonwave99's answer).
Finally:
Why are you putting an anonymous function within the array of $x? Seems like a path that will lead to problems down the road....
Your variable $YesNo needs to be visible in the scope of your anonymous function. You need to add global $YesNo as the first statement in that function:
So
$x = array("active"=>function(){return abc($YesNo);});
becomes
$x = array("active"=>function(){global $YesNo; return abc($YesNo);});
... also "value"=>"No" should be "value"=>"Yes" if you want it to return "Yes"
Is is possible to concatenate an object's name?
The below doesn't seem to work..
Trying to call $node->field_presenter_en;
$lang = 'en';
$node->field_presenter_.$lang;
${$node->field_presenter_.$lang};
Thanks!
Try:
$field_presenter = 'field_presenter_'.$lang;
$node->$field_presenter;
This is called variable variables. More information here:
http://php.net/manual/en/language.variables.variable.php
Edit:
The user nickb has suggested a much more elegant solution below, and I will incorporate into this answer for easier reading (nickb: please let me know if you want me to remove this):
$node->{'field_presenter_'.$lang}
$field_presenter = 'field_presenter_'.$lang;
$node->$field_presenter;
<?php
class A {
public $prop = 'hello';
}
$a = new A();
echo $a->{'pro' . 'p'}; // hello
It know it can be done with get_class($variable).
The problem is that my $object is actually a string containing the variable name.
so:
$object = new MyClass();
$var = '$object';
$class = get_class($var); // obviously fails
I can't use get_class($object), because I don't have direct access to that variable (I'm producing the $var string from parsing a PHP expression using token_get_all())
I tried using eval(sprintf('return get_class(%s);', $var)), but it doesn't work because the variable appear undefined from eval's scope :(
Is there a way to do this?
I need to know the class in order to pass it to ReflectionMethod, so I can get information about a method (the next element in the PHP expression).
NVM: I'm pretty sure it is not possible. Sorry for asking:)
you can do
$var = new $object();
Try using variable variables: http://php.net/manual/en/language.variables.variable.php
Something like:
$var = 'object';
$class = get_class( $$var );
you can do the following
$ref = ltrim($var, '$');
get_class($ref);
func($name1) should return name1
Is it possible?
Here's a function that does it.
function var_name (&$iVar, &$aDefinedVars)
{
foreach ($aDefinedVars as $k=>$v)
$aDefinedVars_0[$k] = $v;
$iVarSave = $iVar;
$iVar =!$iVar;
$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
$iVar = $iVarSave;
return $aDiffKeys[0];
}
Call it like this
$test = "blah";
echo var_name($test, get_defined_vars());
That will print out "test".
I originally found that function over here You can also do it by iterating over the array returned by get_defined_vars(). That might be a bit easier to understand.
No, there is no way to get the name of a variable in PHP.
When calling a function, that function will only receive the content of the variable, and not the "variable itself" -- which means a function cannot find out the name of the variable that was passed to it.
Good Idea ? No
Any usecase you where you should do it ? No
Proof of concept ? Sure !
<?php
a($test);
function a($x) {
$trace = debug_backtrace();
$file = file($trace[0]['file']);
$line = $file[$trace[0]['line']-1];
var_dump($line); // Prints "a($test);" Do the Stringparsing and your done
}
Yes, this takes the "easy" by reading the sourcefile, it is also doable by using a php extension called "bytekit" that gives you userland access to the php opcodes and work from there.
No.
When you define a function, you specify a local variable name for it to have inside the scope of that function. PHP will pass the function the appropriate value, but the symbol is no longer in scope.
You could look into using "variable variables" as an alternative, however.
Obviously, it is possible for sufficiently high values of crazy.
The comments on this page include several techniques:
http://php.net/manual/en/language.variables.php
lucas dot karisny at linuxmail dot org's answer works on my machine:
http://www.php.net/manual/en/language.variables.php#49997
YMMV.
I'm using a template engine that inserts code in my site where I want it.
I wrote a function to test for something which is quite easy:
myfunction() { return '($this->data["a"]["b"] ? true : false)'; }
The problem is, $this->data is private, and I can't access it everywhere, so I have to use getData(); which causes my problem.
$this->getData()['a']['b']
does not work, and assigning the value first doesn't either because it will be used directly in an if() block.
Any ideas?
Since PHP 5.4 it's possible to do exactly that:
getSomeArray()[2]
Reference: https://secure.php.net/manual/en/language.types.array.php#example-62
On PHP 5.3 or earlier, you'll need to use a temporary variable.
You cannot use something like this :
$this->getData()['a']['b']
ie, array-access syntax is not possible directly on a function-call.
Youy have to use some temporary variable, like this :
$tmp = $this->getData();
$tmp['a']['b'] // use $tmp, now
In your case, this probably means using something like this :
function myfunction() {
$tmp = $this->getData();
return ($tmp['a']['b'] ? true : false);
}
You have to :
first, call your getData() method, and store its return value in a temporary varibale
then, use that temporary variable for your test
You don't have much choice about that, actually...
Ok... apparently there really isn't a better way, so I'm going to answer myself with a not so beautiful solution:
I created the function:
arrayGet($array, $index) { return $array[$index]; }
And used it like this:
myfunction() { return '(arrayGet(arrayGet($this, "a"), "b") ? true : false)' }
This is not pretty but works.
$this->data is always accessible, if it is protected. $object->data is not accessible from everywhere, so if you're returning $this in your code, and it is evaluated as such, it should be ok.
Btw, there is a bug in your code: The quotes need to be escaped.
myfunction() { return '($this->data[\'a\'][\'b\'] ? true : false)'; }
It is possible from PHP version 5.4.
If you don't want a temporary variable for that and your PHP version is less, than 5.4, than you still can use a few built in functions to get the first or the last element:
$x = 'first?last';
$first = array_shift(explode('?', $x));
$last = end(explode('?', $x));
$last2 = array_pop(explode('?', $x));
Edit:
!!! Please note, that in later versions( 5.4+ ) PHP will throw a notice, because end only expects variables as parameter.