PHP put the variable name in a string - php

I have a function for dumping variables on the screen and what I'd like to do is to show the name of the variable next to the value of the variable, so it would output something like this:
function my_function($var) {
return '<pre>' . var_dump($var) . '</pre>';
}
$myVar = 'This is a variable';
echo my_function($var); // outputs on screen: myVar has value: This is a variable
$anotherVar = 'Something else';
echo my_function($anotherVar); // outputs on screen: anotherVar has value: Something else
How can I do this ?

PHP offers no simple way of doing this. The PHP developers never saw any reason why this should be neccesary.
You can however use a couple of workarounds found here:
Is there a way to get the name of a variable? PHP - Reflection and here: How to get a variable name as a string in PHP?

Probably, debug_backtrace() function in such case will be the most effective:
function my_function($var) {
$caller = debug_backtrace()[0];
$file = $caller['file'];
$lineno = $caller['line'];
$fp = fopen($file, 'r');
$line = "";
for ($i = 0; $i < $lineno; $i++) {
$line = fgets($fp);
}
$regex = '/'.__FUNCTION__.'\(([^)]*)\)/';
preg_match($regex, $line, $matches);
echo '<pre>'. $matches[1]. ": $var</pre>";
}
$anotherVar = 'Something else';
my_function($anotherVar);
// output: $anotherVar: Something else

Related

if $string found break else add new not working

I am doing something wrong?
This doesn't take any effects
$id = $_POST['id'];
$tudof = "\n #QTP ".$qtp." ID: ".$id;
echo "\n";
$fp = fopen('../../../ids.txt', 'a+');
$searchString = "id";
if(exec('grep '.escapeshellarg($searchString).' '.$fp)) {
break;
} else {
// Add the new name
fwrite($fp, $writef);
fclose($fp);
}
How to search a string and if not found add a new name?
I believe this will work.
I use file_get_contents to load the file as one string and use strpos to find "id".
I also include a preg_match version since strpos will match "lid" for "id" which preg_match won't.
$id = $_POST['id'];
$tudof = "\n #QTP ".$qtp." ID: ".$id;
echo "\n";
$str = file_get_contents('../../../ids.txt');
$searchString = "id";
if(strpos($str, $searchString) !==false) {
// Found it! Break won't work.
// If you want to stop all php code use exit;
} else {
// Add the new name
// Not sure what you do here but use file_put_contents
file_put_contents('../../../ids.txt', $str);
}
// Preg_match
if(preg_match("/\b " . $str ."\b/", $searchString)) {

View a PHP Closure's Source

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!

PHP dynamic string update with reference

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\");");
?>

Sorting strings, in a function, is my logic faulty or?

i need to sort some strings and match them with links, this is what i do:
$name_link = $dom->find('div[class=link] strong');
Returns array [0]-[5] containing strings such as NowDownload.eu
$code_link = $dom->find('div[class=link] code');
Returns links that match the names from 0-5, as in link [0] belongs to name [0]
I do not know the order in which they are returned, NowDownload.Eu, could be $code_link[4] or $code_link [3], but the name array will match it in order.
Now, i need $code_link[4] // lets say its NowDownload.Eu to become $link1 every time
so i do this
$i = 0;
while (!empty($code_link[$i]))
SortLinks($name_link, $code_link, $i); // pass all links and names to function, and counter
$i++;
}
function SortLinks($name_link, $code_link, &$i) { // counter is passed by reference since it has to increase after the function
$string = $name_link[$i]->plaintext; // name_link is saved as string
$string = serialize($string); // They are returned in a odd format, not searcheble unless i serialize
if (strpos($string, 'NowDownload.eu')) { // if string contains NowDownload.eu
$link1 = $code_link[$i]->plaintext;
$link1 = html_entity_decode($link1);
return $link1; // return link1
}
elseif (strpos($string, 'Fileswap')) {
$link2 = $code_link[$i]->plaintext;
$link2 = html_entity_decode($link2);
return $link2;
}
elseif (strpos($string, 'Mirrorcreator')) {
$link3 = $code_link[$i]->plaintext;
$link3 = html_entity_decode($link3);
return $link3;
}
elseif (strpos($string, 'Uploaded')) {
$link4 = $code_link[$i]->plaintext;
$link4 = html_entity_decode($link4);
return $link4;
}
elseif (strpos($string, 'Ziddu')) {
$link5 = $code_link[$i]->plaintext;
$link5 = html_entity_decode($link5);
return $link5;
}
elseif (strpos($string, 'ZippyShare')) {
$link6 = $code_link[$i]->plaintext;
$link6 = html_entity_decode($link6);
return $link6;
}
}
echo $link1 . '<br>';
echo $link2 . '<br>';
echo $link3 . '<br>';
echo $link4 . '<br>';
echo $link5 . '<br>';
echo $link6 . '<br>';
die();
I know they it finds the link, i have tested it before, but i wanted to make it a function, and it messed up, is my logic faulty or is there an issue with the way i pass the variables/ararys ?
I don't know why you pass $i as reference since you use it just for reading it. You could return an array contaning the named links and using it like so :
$all_links = SortLinks($name_link,$code_link);
echo $all_links['link1'].'<br/>';
echo $all_links['link2'].'<br/>';
You will have to put your loop inside the function, not outside.

PHP Read a number from a txt file and make then calculations

I have a file which has only one line, with a number from 1 to 40, and I have the following code:
$file_line = file('../countersaver.txt');
foreach ($file_line as $line) {
$line_result = $line;
}
echo $line;
I have to calculate the result of $line - 1 and echo that result.
But when i do:
$line = $line - 1;
Then it shows $line - 1 and doesn't actually do the calculation.
Your code is weak to changes of the file contents. If someone adds a few blank lines, for example, your code won't work. Try this out instead:
$number = trim(file_get_contents('../countersaver.txt'));
echo $number - 1;
Try replacing
$line = $line - 1;
echo $line
with
$line = ($line -1);
echo $line
This will print 19 instead of 20-1.
I don't see an approved answer here but for anyone looking at this post, if you have a variable that you want PHP to read as a number you can use intval() function. Details covered here...
http://php.net/manual/en/function.intval.php
Try this:
$fin = #fopen("path to file", "r");
if ($fin) {
while (!feof($fin)) {
$buffer = fgets($fin);
}
fclose($fin);
}

Categories