PHP hidden trick or a supported feature? - php

I know that to concatenate strings in php, a dot should be used:
echo 'hello' . ' world'; // hello world
But incidentally i typed this:
echo 'hello' , ' world';
and the result was still hello world without any errors.
Why is it so?
Can we also concatenate using comma?

It's documented in the entry for echo:
void echo ( string $arg1 [, string $... ] )
The two forms are not actually equivalent, since there's a difference in the instant in which functions are evaluated.

No, you cannot concatenate with comma:
<?php
$foo = 'One', 'Two';
?>
Parse error: syntax error, unexpected
','

echo is a language construct, so you don't need parenthesis. But you are "passing" multiple parameters to echo. Think of it as:
echo('hello', ' world');

It's no hidden trick, it's just how echo works. If you have a look at the PHP reference docs for echo, you'll notice that it will echo the list of strings that you throw at it.

echo is a language construct. It is in someway a special function that's defined at Grammar level (I might be wrong on this). It is a function that somehow doesn't follow any of the defined way of defining a function/method as an example and the way of calling them. It "by-passes" some syntax check :)
There's a nice post discussing the difference between language construct & built in functions here in StackOverflow.

echo('hello', ' world');
It's the same as:
echo 'hello', ' world';

Related

Why is echo behaviors different?

Today,
while We were referencing a book, we found out that echo have a multiple parameters, but with few testing, Its giving us weird behavior.
Here is a test:
echo("one", "two");
And here is another:
echo "one", "two";
The first test case is giving error, but second isn't..Why?
The documentation gives you the answer:
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.
http://php.net/manual/en/function.echo.php
So, in short: because echo is not a function - skip the parentheses. You can use parentheses if you want to echo only one parameter, but it's custom not to.
<?php
echo 'Hello'; //Acceptable
echo('Hello'); //Acceptable
echo 'Hello ', 'world'; //Acceptable
echo ('Hello ', 'world'); //Not acceptable
?>

General php format

So, I am just familiarizing myself with php and I see that there are few alternative formats when it comes to writing in php.
What I am confused about is the "dots" or their placements as well other stuffs such as "_".
For example,
<?php
if(!empty($my_post))
{
echo $my_post . ' ' . __('my_post','my_site') . ' + ';
}
?>
It might be a really silly question but could someone explain to me what the function of "dots" in between and just the format itself.
Thanks!
TheSaurus has answered it right. Dots(.) in PHP are the concatenation operators like that plus(+) in java. Whenever you want to build a string with some sub strings, you may use it. There are several other plenty of uses of this, depending on the use.Like One explained in above example.
e.g.:
$line="STACK OVERFLOW";
echo "$line<br/>"
// Some Computation
$line.="is good"; // Here used to concatenate
echo $line
This will output
STACK OVERFLOW
STACK OVERFLOW is good
The dot is the concatenation operator ('.'), which returns the concatenation of its right and left arguments.
<?php
$var = "hello";
$world = "world";
echo "$var" . '$world'; //outputs hello$world
echo "$var" . "$world"; //outputs helloworld
echo "$var" . $world; //outputs helloworld
?>
Read More
The dot
As many have answered before, the dot concatenates strings into a single string. But it's not necessary for bot to be strings. You can concatenate an integer with a string just fine.
<?php
$a = 'Number';
$b = 2;
$c = 'Yay!';
echo $a . $b . $c; // Output: Number2Yay!
?>
The double underscore
In your case, the __() function is just an alias for gettext(): documentation: LINK
Usually, though, the double underscore is used for Magic Methods.
You'll find this piece of text in the documentation:
PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.
You can read all about them here: Magic Methods
P.S. You'll probably find THIS LINK very useful for future reference. I really recommend looking through this list :)
Dots are string concatenation operators in PHP.
So, if I write
$a="3";
$b="text";
echo $a.$b;
The result will be 3text.
If you want to add some space between those;
echo $a.' '.$b;
The result will be 3 text.
Please note that ' ' means space character in string form.
Also, please check other questions before submitting one.

What does { } do within a string?

$name = "jason";
$p = "hello-{hello2}-$name-{$name}";
echo $p;
output :
hello-{hello2}-jason-jason
Came across some examples of prepared statements and noticed this. If its encompassing a variable, it removes them, otherwise it keeps them. Why is this behavior necessary when
echo "$name";
gets you the same result as
echo "{$name}";
or is it just readability?
It's used as a delimiter for variables in strings. This is necessary in some cases, as PHP's string parser isn't Greedy aand will mis-interpret many common structs.
e.g.
$foo = array();
$foo['bar'] = array();
$foo['bar']['baz'] = 'qux';
echo "Hello $foo[bar][baz]";
will actually print
Hello Array[baz]
Because it's parsed as
echo "Hello ", $foo['bar'], "[baz]";
^ ^ ^
string array string
Using {} forces PHP to consider the array reference as single entity:
echo "Hello, {$foo['bar']['baz']}"; // prints "Hello, qux"
It also helps differentiate ambiguous stuff
$foo = 'bar';
echo "$foos" // undefined variable 'foos'
echo "{$foo}s" // variable containing 'bar' + string 's'
It's something called "complex syntax"
From php.net you can go to Complex (curly) syntax section and see many examples.
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$.
Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.
It does not necessarily generate the same output:
$name = 'foo';
$names = 'bar';
echo "Output1: $names";
echo "Output2: {$name}s";
Output
Output1: bar
Output2: foos
Also you can access complex structures via the curly syntax like {$foo->bar}.
This syntax is useful when you want to display variable following some string and you don't want any space between them.
Compare the following:
<?php
$name='John';
echo "My name is $nameathan. I'm twenty years old<br />";
echo "My name is {$name}athan. I'm twenty years old<br />";
It will give you result:
Notice: Undefined variable: nameathan in ... on line 5
My name is . I'm twenty years old
My name is Johnathan. I'm twenty years old
For first echo it will generate notice and won't work as expected because PHP doesn't know that you want to use variable $name in the string and not $nameathan. Using curly braces in second case solves the issue.
Of course you can concatenate string this way:
echo "My name is $name"."athan. I'm twenty years old<br />";
and it also solves the issue but if you have many such variables in string it will be much more convenient to use curly braces.

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

Constants inside quotes are not printed?

This prints apple:
define("CONSTANT","apple");
echo CONSTANT;
But this doesn't:
echo "This is a constant: CONSTANT";
Why?
Because "constants inside quotes are not printed". The correct form is:
echo "This is a constant: " . CONSTANT;
The dot is the concatenation operator.
define('QUICK', 'slow');
define('FOX', 'fox');
$K = 'strval';
echo "The {$K(QUICK)} brown {$K(FOX)} jumps over the lazy dog's {$K(BACK)}.";
If you want to include references to variables inside of strings you need to use special syntax. This feature is called string interpolation and is included in most scripting languages.
This page describes the feature in PHP. It appears that constants are not replaced during string interpolation in PHP, so the only way to get the behavior you want is to use the concatenation that Artefacto suggested.
In fact, I just found another post saying as much:
AFAIK, with static variables, one has
the same 'problem' as with constants:
no interpolation possible, just use
temporary variables or concatenation.
Concatenation has been suggested as the only solution here, but that doesn't work when using syntax like:
define("MY_CONSTANT", "some information");
$html = <<< EOS
<p>Some html, **put MY_CONSTANT here**</p>
EOS;
Of course, the above just puts the text 'MY_CONSTANT' in $html.
Other options include:
define a temporary variable to hold the constant:
$myConst = MY_CONSTANT;
$html = <<< EOS
<p>Some html, {$myConst} </p>
EOS;
if there are many constants, you can get an array of them all and use that:
$constants = get_defined_constants();
$html = <<< EOS
<p>Some html, {$constants["MY_CONSTANT"]} </p>
EOS;
Of course, in such a trivially short example, there's no reason to use the <<< operator, but with a longer block of output the above two may be much clearer and easier to maintain than a bunch of string concatenation!
The question was already answered, but I'd like to provide a more generic insight on this.
In double quotes, PHP recognizes anything starting with a $ as a variable to be interpolated. Further more, it considers array and object access ([] and ->) but only up to a single level. E.g. "$foo->bar" interpolates $foo->bar and $foo->bar->baz does the same thing and treats ->baz as a string literally. Also, the quotes in [] must be ommited for string keys. E.g. "$foo[bar]" interpolates $foo['bar'] while "$foo['bar']" is a syntax error. AFAIK, that's it. To get more functionality, you need the "{$...}" syntax.
The $ here is actually a part of the syntax and it doesn't work without it. E.g. "{FOO}" will not interpolate a constant FOO, it's simply a syntax error. However, other than some strange syntactical restrictions, this construct is actually quite strong and may contain any valid PHP expression, as long as it starts with a $ and is an array access, object access, or a function call. (Maybe some other cases are permitted to. Please let me know, if anyone has a better understanding of this.) The most general solution to your problem would be to define something like the following function somewhere in your code base:
$id = function ($x) {
return $x;
}
It's simply the identity function - it returns whatever you give it. It must be defined as an anonymous function, so you can refer to it as $id with the $.
Now you can use this function to interpolate any PHP expression:
echo "{$id(CONSTANTS)}"
echo "{$id($some + $operators - $as . $well)}"
// etc...
Alternative for PHP versions < 5.3 where you can't use anonymous functoins:
class Util {
function id ($x) { return $x; }
}
$u = new Util;
echo "{$u->id(ANY + $expression . $here)}"
// or...
function id ($x) { return $x; };
$id = 'id';
echo "{$id(ANY + $expression . $here)}"
The native interpolation does not support constants. Still not up to PHP 8.2 (and maybe later on). An alternative to echo is to use printf() or sprintf() for getting the interpolation result as string.
const MY_CONSTANT = "foo";
printf("Hello %s bar!", MY_CONSTANT);

Categories