The code below adds lo after Hel, thus outputs Hello :
$foo = "Hel";
$bar = "lo";
$foo .= $bar;
echo $foo;
If I want to output loHel instead, without using echo $bar . $foo what would you guys do? Just curious if there's simpler way.
There is no equivalent of the inverse of .= (such as =.).
You therefore will have to do it the long hand way.
$foo .= $bar is the same as $foo = $foo . $bar;
so you would have to do
$foo = $bar . $foo;
You can do:
$bar .= $foo
echo $bar;
Alternatively you can use substr_replace to insert one string at the beginning of another as:
$foo = substr_replace($foo,$bar,0,0);
I don't think there is a shorthand way of doing this.
String operators in the PHP manual
$bar = "lo".$foo;
$foo=$bar
$bar .= $foo;
echo $bar; // Will output loHel
$foo .= $bar is just a short form for $foo = $foo . $bar.
Unfortunately there is nothing like a prepend operator in PHP. So you can't avoid using $foo = $bar . $foo.
Related
String that has to be converted
$bar = 'R.m.traders';
$bar = ucwords(strtolower($bar));
output should be
R.M.Traders
You need to add delemeter . also called custom delimeter. You can check here. Anyway try this:
<?php
$bar = 'R.m.traders';
$bar = ucwords(strtolower($bar), "."); //After dot(.) next letter will be in Capital.
echo $bar;
?>
Just Try this Hope it helps
$bar = str_replace('.', ' ', $bar);
$bar = ucwords(strtolower($bar));
$bar = str_replace(' ', '.', trim($bar));
ucwords should be doing the first letter caps. R.m.traders is consider single word. If you give R m traders means you will get R M Traders
Alter way:
$bar = 'R.m.traders';
$bar_array = explode('.',$bar);
if(!empty($bar_array)){
$temp = array();
foreach($bar_array as $bar_arr){
$temp[] = ucwords(strtolower($bar_arr));
}
$bar_array = $temp;
}
$bar = implode('.',$bar_array);
echo $bar;
Is it possible to reflect into or otherwise view the source of a PHP closure object? That is, if I do something like this
$closure = function()
{
return 'Hi There';
};
and then something like this
var_dump($closure);
PHP outputs
object(Closure)[14]
That is, I know the object's a closure, but I have no idea what it does.
I'm looking for a reflection method, function, or debugging extension that will allow me to dump the actual body of anonymous function.
What you can get from PHP is limited, using reflection you can just obtain the parameter signature of the function and the start and ending line of the source code file. I've once wrote a blog article about that: http://www.metashock.de/2013/05/dump-source-code-of-closure-in-php/ ...
It lead me to the following code, using reflection:
function closure_dump(Closure $c) {
$str = 'function (';
$r = new ReflectionFunction($c);
$params = array();
foreach($r->getParameters() as $p) {
$s = '';
if($p->isArray()) {
$s .= 'array ';
} else if($p->getClass()) {
$s .= $p->getClass()->name . ' ';
}
if($p->isPassedByReference()){
$s .= '&';
}
$s .= '$' . $p->name;
if($p->isOptional()) {
$s .= ' = ' . var_export($p->getDefaultValue(), TRUE);
}
$params []= $s;
}
$str .= implode(', ', $params);
$str .= '){' . PHP_EOL;
$lines = file($r->getFileName());
for($l = $r->getStartLine(); $l < $r->getEndLine(); $l++) {
$str .= $lines[$l];
}
return $str;
}
If you have the following closure:
$f = function (Closure $a, &$b = -1, array $c = array())
use ($foo)
{
echo $this->name;
echo 'test';
};
closure_dump() will give the following results:
function (Closure $a, &$b = -1, array $c = array (
)){
use ($foo)
{
echo $this->name;
echo 'test';
};
You see it is imperfect (the array param). Also it will not handle some edge cases properly, especially if closures are nested or multiple inline closures will getting passed to a function in one line. The latter looks most problematic to me. Since, you get only the starting and ending line from reflection, both functions will be on that line in this case and you have no useful information to decide which one of them should get dumped. So far, I didn't found a solution for that, also I'm unsure if there is a solution.
However, in most cases, it should at least being helpful for debugging, as long as you don't rely on it. Feel free to enhance it!
I have this variable
$foo['title'] = 'Hello World';
I want to access this variable from a string.
$string = '$foo["title"]';
How can I display "Hello World" by my variable $string?
I searched an other topic, i found something similar, unfortunately it doesn't work.
$foo['title'] = "Hello, world!";
$bar = "foo['title']";
echo $$bar;
Actually I am not sure I understand you goal.
Do you want maybe this?
$foo['title'] = "Hello, world!";
$bar = "$foo[title]";
echo $bar;
The result:
Hello, world!
This is the same as this:
$bar = $foo['title'];
Or you would like to prepend/append something? Like this:
$bar = 'prepend something ' . $foo['title'] . ' append something';
You need to split the argument to the array away from the variable name, and then enclose the variable name in curly braces. So:
// get array argument
$matches = array();
preg_match("/\['(?s)(.*)'\]/", $bar, $matches);
$array_arg = $matches[1];
// get variable name
$arr = explode("[", $string, 2);
$var_name = $arr[0];
// put it together
${$var_name}[$array_arg]
Is there any way to do this:
$myVar = 2;
$str = "I'm number:".$myVar;
$myVar = 3;
echo $str;
output would be: "I'm number: 3";
I'd like to have a string where part of it would be like a pointer and its value would be set by the last modification to the referenced variable.
For instance even if I do this:
$myStr = "hi";
$myStrReference = &$myStr;
$dynamicStr = "bye ".$myStrReference;
$myStr = "bye";
echo $dynamicStr;
This will output "bye hi" but I'd like it to be "bye bye" due to the last change. I think the issue is when concatenating a pointer to a string the the pointer's value is the one used. As such, It's not possible to output the string using the value set after the concatenation.
Any ideas?
Update: the $dynamicStr will be appended to a $biggerString and at the end the $finalResult ($biggerString+$dynamicStr) will be echo to the user. Thus, my only option would be doing some kind of echo eval($finalResult) where $finalResult would have an echo($dynamicStr) inside and $dynamicStr='$myStr' (as suggested by Lawson), right?
Update:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
$finalStr = "hi ".$str();
$myVar = 3;
echo $finalStr;
I'd like for this to ouput: "hi I'm number 3" instead of "hi I'm number 2"...but it doesn't.
The problem here is that once a variable gets assigned a value (a string in your case), its value doesn't change until it's modified again.
You could use an anonymous function to accomplish something similar:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
echo $str(); // I'm number 2
$myVar = 3;
echo $str(); // I'm number 3
When the function gets assigned to $str it keeps the variable $myVar accessible from within. Calling it at any point in time will use the most recent value of $myVar.
Update
Regarding your last question, if you want to expand the string even more, you can create yet another wrapper:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
$finalStr = function($str) {
return "hi " . $str();
}
$myVar = 3;
echo $finalStr($str);
This is a little simpler than I had before. The single quotes tell PHP not to convert the $myVar into a value yet.
<?php
$myVar = 2;
$str = 'I\'m number: $myVar';
$myVar = 3;
echo eval("echo(\"$str\");");
?>
In PHP I can say
$noun = "bird";
$adjective = "warm;
echo <<<EOT
The $noun is very $adjective
EOT;
and it will output
The bird is very warm
Is there a way to do this with functions?
function getNoun() { return "bird"; }
function getAdjective() { return "warm"; }
echo <<<EOT
The getNoun() is very getAdjective()
EOT;
and output
The bird is very warm
You can use variable functions, though they're rather frowned on upon as they're not far different from variable variables...
$a = 'getNoun';
$b = 'getAdjective';
echo <<<EOT
The {$a()} is very {$b()}
EOT;
You could store it in a variable before using it:
$noun = getNoun( );
$adj = getAdjective( );
echo <<<EOT
The {$noun} is very {$adj}
EOT;
echo "The ";
echo getNoun();
echo " is very ";
echo getVerb();
Or maybe even (not 100% sure):
echo "The " . getNoun() . " is very " . getVerb();
Here is a solution using variable functions, although not exactly:
$noun=function($type){
return $type;
};
$adjective=function($adj){
return $adj;
};
echo "{$noun("Robin")} was very {$adjective("Warm")}";