Use string instead of "echo"? - php

Is there any way at all to make a variable work like echo, as such:
$x = "echo";
$x "Hi there!";
If you understand what I mean? I've seen it done before only the variable was "system" and the code was
//taking $x = "system"
$x(blablabla);
Any ideas?

From the notes on echo's manual page:
Note: Because this is a language construct and not a function, it cannot be called using variable functions.
If you insist, you could say like eval "$x \"stuff\";";, but other than that or creating a function and using it instead, you're kinda out of luck.

You mean like this:
$x = 'printf';
$x('Hi there');
?
echo is a language construct, not a function, so it won't work

Related

"Mega" Dynamic acces to static method/property in PHP 5.3?

Having this 2 classes:
class run {
public static $where = "there";
}
class there {
public static $place_name = "A beautiful place..";
}
To get place_name I can do this:
$place = "there";
echo $place::$place_name;
But I might want to do something like this at some point..:
echo {$run::$where}::$place_name;
Obviously, the last snippet doesn't work.
Is there any way to make it do work?
If you do not want to use a variable (as you said in a comment), think twice. Variables are cool in PHP, very fast and just the needed glue to work-around its limited parser (which of it was said makes PHP quite fast). So why not use a variable here? It's easy to type and quickly done.
If you don't want the variable and as we already have found out that PHP's syntax is limited, you can at least write a one-liner with PHP 5.4+ to achieve what you're looking for:
echo (new ReflectionClass((new ReflectionClass($run))->getStaticPropertyValue('where')))->getStaticPropertyValue('place_name');
which then finally should make visible that using a variable is more comfortable:
echo (unset) $place = $run::$where, $place::$place_name;
Demo: http://eval.in/13942

PHP Globals and Reference Difference Confusion

Could some one please explain to me what the difference in the following is:
$var = 'something';
function myFunc(){
global $var;
// do something
}
and (note: the reference sign &)
$var = 'something';
function myFunc(&$var){
// do something
}
I can't understand the difference between these two methods.
Update
Hmmm... I think i'm getting alittle confused here :)
$var = 1;
$var2 = 2;
function myFunction(){
global $var, $var2;
$var = $var + $var2;
}
// echo $var would return 3 here.
$var = 1;
$var2 = 2;
function myFunction(&$a, &$b){
$a = $a + $b;
}
// echo $var would return 3 here aswell.
I understand those part already, But what i don't understand is the difference between these two approaches, am i wrong to assume that these two approaches are technically the same thing, with different concept of how they are wrote by the coder and also how they are handled by PHP?
If i'm wrong to assume this, then it would really help if you could provide better examples, maybe something that can be accomplished using only one of the above approaches?
ok, i noticed one difference while writing This Update, which is that when doing references i can chose new variable names while keeping the pointer to the variable in the functions scope.
In the second code block, the external $var and the internal $var are the same element. On the other hand, the third code block behaves a lot more like the first -- but you can access and modify the variable from the sending function; in the first code block, any edits you make to the variable internally are not available outside of the scope of the function.
EDIT to match the edits to the question.
The & means we are passing the variable by reference. The best way to describe it is by example.
function test2(&$var) { $var = 2; }
function test() {
$abc = 1;
test2($abc);
echo $abc;
}
test();
This code will print a 2 to the screen.
$var = 0;
function test()
{
global $var;
$var = 1;
}
test();
echo $var;
This will print 1;
In the first example, the local $var variable inside myFunc() will be assigned by reference to the variable with the same name that exists in the global scope (accessible through the superglobal $GLOBALS). PHP translates that to something like:
$var = 'something';
$GLOBALS['var'] = &$var;
function myFunc(){
$var = &$GLOBALS['var'];
// do something
}
In the second example, you pass the variable explicitly to the function, thus it is not taken from the global scope.
$var = 'something';
$GLOBALS['var'] = &$var;
function myFunc(&$var){
// do something
}
myFunc($var);
Both examples will reference the exact same variable, but using different mechanisms.
There is no technical difference at all between your two examples; they will always behave in an identical manner.
That leaves us looking for other types of differences, and there is a pretty significant code quality difference here: In the first version, looking at the call site will not tell you that the function depends on the global. In the second one it will (it's being passed in as a parameter). So the second form is, in my book at least, superior.
In addition, another difference (although one that does not apply to this example) is that the first form can only be used if your variable is in the global scope to begin with; the second will work everywhere.
You should also take into account that both these methods have an in/out argument. Normally you would not be writing code like this if it were just one argument (since you can return the out value instead) so it's interesting to consider the case where more than one arguments are being given. This is a pretty rare, and it can be argued that it's better to just return an array with multiple values rather than take multiple arguments by reference to make the code even easier to follow.
So in conclusion:
They do the same thing
If you are going to use one of them, prefer the second form (clearer, more flexible)
Consider using none of them and doing things otherwise if it doesn't require writing a substantial amount of additional code
One passes by value and one passes by reference:
By value:
$var = 'something';
function myFunc($var){
$var = 'hello';
}
echo $var; //something
By reference:
$var = 'something';
function myFunc(&$var){
$var = 'hello';
}
echo $var; //hello
For more information, the PHP manual has a page on passing by reference: http://php.net/manual/en/language.references.pass.php
In the case of globals, you are essentially pulling a variable from the global scope and using it inside of the function. It's like implicitly passing by reference.
This page, in particular the global section explains: http://us.php.net/manual/en/language.variables.scope.php
Please note that globals should typically be avoided. The short version of why is because they make knowing the state of a program difficult, and later changes can cause unexpected side effects.

Testing variables in PHP

Earlier today I tried to do this:
Example 1:
<?php
echo $myVar || "rawr";
?>
I thought this might print out $myVar if it was set, and print "rawr" if not.
It printed a 1, I assume this is the result of the OR test.
What I then tried was this:
Example 2:
<?php
if ($myVar)
{
echo $myVar;
}
else
{
echo "rawr";
}
?>
Which is what I was trying to accomplish.
I think I understand why the first prints the results of the OR test rather than one of the variables, and also why I tried it - been spending some time on the bash shell recently :)
Can anyone tell me if there is a way to perform the text in example #2 but in similar syntax to example #1?
PHP 5.3:
echo $myVar ?: 'rawr';
Pre 5.3:
echo $myVar ? $myVar : 'rawr';
If $myVar may not be set you'd have to use isset($myVar) and $myVar as the condition (which then wouldn't work with the shorthand ?: syntax, as this would echo 1 if it was set, rather than the value).
echo (isset($myVar) and $myVar) ? $myVar : 'rawr';
PHP is notoriously inelegant in this department, and there really is no good way of making this test.
As a general solution, you 'd need to use the ternary operator as in empty($var) ? "rawr" : $var. However, in practice what happens is that you have one of two scenarios:
1. Your own variable
In this case where you define the variable yourself, the best solution is to just give it a known default value at the place you define it (possibly with the ternary operator).
2. Inside an array
If the array is one that should not be touched like one of the superglobals, then you can wrap the test inside a function (pretty much that's what everyone does).
If the array is one under your jurisdiction but it comes from an external source, you can use the "add the defaults" trick:
$incoming = array(...);
$defaults = array("foo" => "bar");
// Inject the defaults into $incoming without overwriting existing values
$incoming += $defaults;
At this point you know for a fact that every key inside $defaults also exists inside $incoming.
In PHP 5.3+ it is possible to leave out the second argument:
echo $myVar ?: 'rawr';
This is probably closest to what you want.
Try this:
echo $myVar = ($myVar) ? $myVar : 'rawr';
or
echo $myVar ? $myVar : 'rawr';
I think you want to use something like var_dump($varname) or isset($varname) ?
it's matter of operator precedence. you can't do that.
two points as a food for thought
if $myVar is not set, you'll get an error message, not "wawr";
by the time you're going to echo some variables, every one of them should be defined and have value. That will make your template clean and readable.
Try
echo ($myVar != null ? $myVar : "Rawr!");

Why can I not use a variable to store echo() like I can other functions?

I'm just trying to figure out why I can't do this:
<?php
$a = "echo";
$a("test");
?>
It just returns PHP Fatal error: Call to undefined function echo() in Command line code on line 1
When I can do this:
<?php
$a = "explode";
var_dump($a("|","1|2|3"));
?>
and get the expected result.
Edit: Found a solution to my problem (as inspired by the various answers below).
Create an anonymous function inside the variable $a as so:
$a = function($a){echo $a;};
This will only work in PHP 5.3 or greater though.
That's because echo is not a function but a language construct.
Try with print() instead. That should work fine.
EDIT: As pointed out in the comments print is also a language construct and won't work! Only solution is wrapping echo or print in a user defined function then.
<?php
function output($str){
return print $str;
}
$a = "output";
$a("Lorem Ipsum ...");
?>
Echo isn't a function. It's a language construct that resembles a function but it doesn't return any values. Because of this, it cannot be used in variable functions ($foo = 'echo'; $foo ('hello world'); doesn't work)
You will have to use a different output method from echo (such as print) to do what you want.
Maybe because explode is a function whereas echo is a language construct. Notice there are no brackets when using echo.
look in docs
echo() is not actually a function (it is a language construct), so you
are not required to use parentheses with it. echo() (unlike some other
language constructs) does not behave like a function, so it cannot
always be used in the context of a function. Additionally, if you want
to pass more than one parameter to echo(), the parameters must not be
enclosed within parentheses.
Because echo is not a function, it is a built in part of PHP.
See here: http://www.php.net/manual/en/functions.variable-functions.php

Is is possible to call a variable that has been assigned after the call (PHP)?

The title is in the question (EDIT: :P I mean the question is in the title), basically can I call variable $x before defining it further down the page?
Short answer, no.
Long answer, noooooooooooooooooooooooooooooooooooooooooo.
But seriously, you can refer to it, it just won't do what you want.
Depending on how strict your warnings on you can call an undeclared variable as much as you want. However until you assign it a value it won't have a value.
I am not quite sure to understand your point but if you want to write
echo $x;
$x = "2";
you will not get "2" as a result.
PHP will usually not issue a warning when you reference a variable that has not yet been assigned a value. PHP will create it on the fly and assign it the null value which will then be casted to whatever scope you have. For example
$a = $b + 5;
echo $a;
will print 5 because in this case $b will be interpreted as beeing 0.
I hope this will help
Jerome
No, the execution goes down the file. You can use a function though, to call later on once the variable has been defined. For example:
<?php
function meow() {
echo $kitty_noise;
}
?>
And then later on down the file...
<?php
$kitty_noice = 'meowwwwww!';
meow();
?>
Horrible example....

Categories