Line number variable php

PHP function: find argument’s variable name, and function calls line number

This isn’t something you can easily do, as the function parameter is an expression which is evaluated before the function is called. Thus, the function can only see the value of that expression, and not the expression itself.

If you really want to do this, you could use debug_backtrace to find the file and line number of the caller, extract that line from the source file, then parse out the expression from the function call. Here’s a proof-of-concept:

function dump($value) < $trace=debug_backtrace(); $expr=""; if (isset($trace[0]['file'])) < $lines=file($trace[0]['file']); $line=$lines[$trace[0]['line']-1]; $expr=$line; $expr=preg_replace('/\s*dump\(/i','', $expr); $expr=preg_replace('/\);\s*/', '', $expr); >echo "$expr is $value\n"; > //examples. $a=10; dump($a); dump($a+10); 

Clearly nuts. But it works 🙂 You could of course simply pass the name in along with the variable!

Read More

You cannot get variable name.

Though you can make it just

Your Common Sense 155649

The problem with this is that the variable should have a unique value 🙁

function log_var($var, $line) < $var_name = 'unknown'; foreach($GLOBALS as $var_name =>$value) if ($value === $var) $var_name = $var_name; $line--; $filepath = 'log-' . date('Y-m-d'). '.txt'; $message = "$line, $var_name = $var\n"; $fp = fopen($filepath, "a"); fwrite($fp, $message); fclose($fp); @chmod($filepath, 0666); return TRUE; > $a = 'hello'; log_var($a, __LINE__); 

Clarification: you should NOT try to do things like this. it’s not recommend and there are probably better ways to do what you want.

Similar Question and Answer

I don’t know if it can be done, that you get the line number of where the variable is set, what you can do:

function log_var($var, $var_name) < $backtrace = debug_backtrace(); $line = $backtrace[0]['line']; // get's the line of the call for log_var $line--; $filepath = 'log-' . date('Y-m-d'). '.txt'; $message = "$line, $var_name = $var\n"; $fp = fopen($filepath, "a"); fwrite($fp, $message); fclose($fp); @chmod($filepath, 0666); return TRUE; >
23 $a = 'hello'; 24 log_var($a,'$a'); 25 $b = 'bye'; 26 log_var($b,'$b'); 

and the output will, look like this:

I don’t believe you can get it any better. But if someone knows how to get it, i’m willing to learn

jigfox 17852

You might be able to do something close with Reflection. Aside from that, though, there’s not much else.

I played with the function provided by Paul Dixon (accepted answer) and got it into the shape really doing what I want. This could act as a poor-man’s debugger, and I hope it will be useful to someone.

Here is the function and example usage/output:

function dump($value) < $trace=debug_backtrace(); $expr=""; if (isset($trace[0]['file'])) < $myline = $trace[0]['line']; $myline--; $lines=file($trace[0]['file']); $line=$lines[$trace[0]['line']-1]; $expr=$line; $expr=preg_replace('/\s*dump\(/i','', $expr); $expr=preg_replace('/\);\s*/', '', $expr); >$handle = @fopen(__FILE__, "r"); if ($handle) < for ($l=1; $l < $myline+1; $l++) < $buffer = fgets($handle); >> fclose($handle); $message = "$myline \t $buffer \t $expr = $value \n\n"; $filepath = 'log.txt'; $fp = fopen($filepath, "a"); fwrite($fp, $message); fclose($fp); @chmod($filepath, 0666); return TRUE; > 

And here is sample usage (numbers represent line numbers in actual code):

41 //examples. 42 $a='hello'; 43 dump($a); 44 45 $b = 'bye'; 46 dump($b); 47 48 $c = date('y-m-d'); 49 dump($c); 50 51 $c = $a . ' and then ' . $b; 52 dump($c); 

The example will produce this output in the log file:

42 $a='hello'; $a = hello 45 $b = 'bye'; $b = bye 48 $c = date('y-m-d'); $c = 10-05-20 51 $c = $a . ' and then ' . $b; $c = hello and then bye 

Majid Fouladpour 28248

More Answer

  • PHP — Is global using to get a variable for example out of the function localscope and aslo out of the page itself without using require or include?
  • JS passing variable to .php, php returning based on variable, displayed by javascript, using AJAX and triggers with bind(‘input’, function ()
  • php find to array and convert to variable
  • JS passing variable to .php, php returning based on variable, displayed by javascript, using AJAX and triggers with bind(‘input’, function ()
  • php find to array and convert to variable
  • Global variable inside class and function PHP
  • PHP MYSQL How to find if a variable exists in mysql_fetch_assoc and its position in the array then set result as variables
  • PHP variable concatenation and text file line breaks
  • PHP function for checking POST security and storing variable
  • PHP checking if method_exists using an variable obtained by function calls
  • PHP — Regular Expression — Arrays — Find the last number and add them together
  • php function variable arguments
  • Find a string in a text file and add text at the beginning to that line in php
  • How to find number of days between a field date and current date using php
  • PHP Find Function start and end
  • Which PHP Array Function Should Be Used To Match a String to the First Part of a Delimited Line and Return the Second Part of the Delimited Line
  • Echoing a variable in php gives one number and setting the variable to a cookie and evaluating the cookie gives another?
  • How to send php variable from Colorbox iFrame to parent; and how to have a function involving said variable run on parent without reload
  • php validation function for name that allow UTF-8 characters plus — (minus) and space
  • Turn PHP variable into Javascript variable and use that Javascript variable as an argument in a Javascript function
  • PHP Find a line in a text file and delete the line
  • PHP — Using a variable as the name of another variable, inside a function
  • class public variable calls compatible in PHP 7.0 and PHP 5.6
  • how can i pass variable in php form to another function with arguments in php codeigniter
  • Using JavaScript, how might I be able to create a function that calls from a PHP file to add keys and properties to a JSON file?
  • Function to find a string inside another string and then find any numbers after that string in PHP
  • Change the sorting of every 5 array of number from ascending to descending and vice versa without using php built in function
  • Passing variable from Javascript to PHP and back
  • MongoDB find query with $and $or and $nearSphere in php
  • Passing PHP variable between files and inserting the variable into a SQL table
  • a php extension crashed — convert memory address to line number
  • Converting a JavaScript function to PHP and it doesn’t produce the expected output
  • Use PHP variable in javascript later and from different files
  • pass variable to function using same name
  • PHP run query off each array variable and return results in table
  • How to edit this php check function and add additional?

More answer with same ag

  • adding comments using php and html
  • Database Connection with SQLSRV drivers in OOP without PDO
  • ‘EM_Colorswatches_Helper_Data’ not found in /public_html/app/Mage.php on line 547
  • Link Styling won’t apply to links for some reason
  • how to call a PHP class function in another page by a link
  • PHP flush() function not working
  • Unable send data to php file via ajax
  • How to make a function return an array in php?
  • Remove all elements of an associative array if they have the a specific word in the key
  • Resize image with ratio using PHP
  • PHP mb_ereg_replace deleting additional characters beyond each unicode search target
  • (PHP/Zend) Fatal error: Class ‘fooClass’ not found in /foo/path
  • Display php echo in another html file
  • PHP Loop — can’t get closing tag to repeat for each group
  • Setting a default js url in a header
  • How to set up CSS/JS cache busting using PHP and Git on high traffic site?
  • How to take textbox value in php if created by js
  • Can PHP curl return an object with body and headers in a single request?
  • Deploy PHP application and restrict code changes
  • pagination in php with hash in url
  • why is flush() not executing data right away? php
  • How to get url part php?
  • simple_html_dom find all elements that ONLY contain certain text
  • Getting data through a PHP file using AJAX+JQuery
  • PHP mail with SMTP
  • How can I have multiple websites all checkout on a common domain?
  • Redirecting to other page with header
  • Clone div and append value from textarea on submit on multiple forms blocks jquery
  • Query to Yii CDbCriteria
  • Issues with WAMP server after installing OSGeo4W
  • When click on search, the data displays, but when i click again, the data disappear
  • Populating dropdown menus using XMLHTTPREQUEST object
  • Linking to a download in HTML
  • how to maintain users history on website in php?
  • MySQLi: Number of variables doesn’t match number of parameters in prepared statement
  • How do I get preg replace to work when the url contains a hashtag
  • php split string by capital letter but ignore TLA. Also with TLA at the end of the word
  • Validate if an application is at the server
  • PHP and MySqli getting all results
  • Best method of uploading large files on server
  • OOP — Classes and Subclasses — Call subclass method
  • WebPush failing to send
  • Combine form values under one name using GET method
  • how to install pecl mail parse on mamp?
  • Forms Help Password and Confirm Password
  • How to recognise if user clicked out of text input and run php in that event
  • wordpress theme checkbox
  • output array in foreach
  • pdo binding not giving value
  • How to send multiple mails in PHP?

Источник

xml_get_current_line_number

Получает номер текущей строки для заданного XML-анализатора.

Список параметров

Ссылка на анализатор XML для получения номера строки.

Возвращаемые значения

Функция возвращает номер строки согласно текущему положению указателя анализатора.

Список изменений

Версия Описание
8.0.0 Параметр parser ожидает экземпляр XMLParser ; ранее ожидался корректный xml ресурс ( resource ).

Смотрите также

  • xml_get_current_column_number() — Получает от XML-анализатора номер текущего столбца
  • xml_get_current_byte_index() — Получает текущий для XML-анализатора байтовый индекс

User Contributed Notes

Оцените статью