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.
Related
This question already has answers here:
How can I replace a variable in a string with the value in PHP?
(13 answers)
Closed 8 years ago.
The only way I've found to interpolate a string (that is, expand the variables inside it) is the following:
$str = 'This is a $a';
$a = 'test';
echo eval('return "' . $str . '";');
Keep in mind that in a real-life scenario, the strings are created in different places, so I can't just replace 's with "s.
Is there a better way for expanding a single-quoted string without the use of eval()? I'm looking for something that PHP itself provides.
Please note: Using strtr() is just like using something like sprintf(). My question is different than the question linked to in the possible duplicate section of this question, since I am letting the string control how (that is, through what function calls or property accessors) it wants to obtain the content.
There are more mechanisms than PHP string literal syntax to replace placeholders in strings! A pretty common one is sprintf:
$str = 'This is a %s';
$a = 'test';
echo sprintf($str, $a);
http://php.net/sprintf
There are a ton of other more or less specialised templating languages. Pick the one you like best.
Have you heard of strtr()?
It serves this very purpose and is very useful to create dynamic HTML content containing information from a database, for example.
Given the following string:
$str = 'here is some text to greet user {zUserName}';
then you can parse it using strtr():
$userName = 'Mike';
$parsed = strtr($str,array('{zUserName}'=>$userName));
echo $parsed; // outputs: 'here is some text to greet user Mike'
While sprintf is faster in some regards, strtr allows you to control what goes where in a more friendly way (sprintf is not really manageable on very long strings containing, say, a hundred placeholders to be replaced).
Here is a possible solution. I am not sure in your particular scenario if this would work for you, but it would definitely cut out the need for so many single and double quotes.
<?php
class a {
function b() {
return "World";
}
}
$c = new a;
echo eval('Hello {$c->b()}.');
?>
What does the following command do in PHP?
. $string // ($string is something which I declared in the program)
On its own, that does nothing at all (it's not valid syntax). However, if you have something like this:
<?php
$string1 = "Hello ";
$string2 = "world!";
$string = $string1 . $string2;
echo $string;
?>
You will see Hello world!. The . is the string concatenation operator.
Taken alone, this is a syntax error. The dot . is the concatenation operator that converts its arguments to strings and concatenates them. For example,
<?php
$string = "x";
$s = 42 . $string;
// $s is now "42x"
Your statement would throw back an error.
The "dot" is a string concatenator. That is, it helps you to combine strings together into another string.
Example.
$full = $part1 . $part2;
Concerning getting started: That's a difficult question. PHP.NET will be your functional looking site. Google-ing just about anything on PHP will direct you there. I'd look at getting a localhost setup of PHP/MySQL/Apache. If you're on a Windows machine, you can get a WAMP server setup.
http://www.wampserver.com/en/
This will drastically speed up your development and testing time. Don't try to FTP everything up to a Web server, as this approach will waste away 10-15% of your working time. Work smart - work local.
Find an existing project (Open Source) with a great community and just try to start something. For example, I recently created DogFriendlyOlrando.com based on WordPress. I was curious as to the abilities of WordPress. It was a fun little project and gave me a good understanding of WordPress' capabilities. You'll learn the most from just diving in and doing. Good luck!
Two string operators are available. The first is the concatenation operator ('.') that returns its right and left argument concatenation.
Second is the concatenation operator of assignment ('.='), which adds the right-hand argument to the left-hand argument. For further details, please read Assignment Operators
The output is displayed directly to the browser like as a given below:
. $string // ($string is something which I declared in the program)
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';
This might be a silly question but it struck me, and here i ask.
<?php
$x="Hi";
$y=" There";
$z = $x.$y;
$a = "$x$y";
echo "$z"."<br />"."$a";
?>
$z uses the traditional concatenation operator provided by php and concatenates, conversely $a doesn't,
My questions:
by not using the concatenation operator, does it effect the performance?
If it doesn't why at all have the concatenation operator.
Why have 2 modes of implementation when one does the work?
Only slightly, since PHP has to parse the entire string looking for variables, while with concatenation, it just slaps the two variables together. So there's a tiny performance hit, but it's not noticeable for most things.
It's a lot easier to concatenate variables like $_SERVER['DOCUMENT_ROOT'] using the concatenation operator (with quotes, you have to surround the variable in brackets or remove the single quotes in the array index; plus it just makes the string look all ugly). Plus, the concatenation operator allows more flexibility for formatting. For example, you can break up a long string literal onto multiple lines and then concatenate the different parts of it:
$blah = "This is a really really long string. I don't even know how " .
"long it is, but it's really long. Like, longer than an eel " .
"or even a boa constrictor. Wow.";
You can also use the concatenation operator to directly include return values from functions in a string literal (you can't include a function call in a double-quoted string), like this:
$blah = "This has a " . fn_call() . " result, which can't go in the quotes.";
I'm not sure I entirely understand what you're asking here, but I can say that PHP borrows a lot of things from Perl, and one of Perl's mantras is "There's more than one way to do it."
a. Yes. PHP has to parse the string for variables.
b. Because of lines like: echo 'Your Ip address is' . get_ip() . '.';
For reasons A and B.
In some cases your write less with:
$someLongVarName ="Hi";
$someLongVarName .=" there";
VS
$someLongVarName ="Hi";
$someLongVarName = "$someLongVarName there";
Addressing your last question:
Every language has multiple was of doing the same thing. Flexibility is important in every language since any given method may be better the another from situation to situation. The only thing that you should worry about in regards to this is to be consistent in your own code.
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);