Search code examples
phplines

Give a function the __LINE__ variable without needing to declare it


So I am trying to make a variable class meaning I can dynamically name my variables. And I wanted to have a undeclared variable at line x on my code. I managed to make a function be called like so:

function ($varname, $line = 0) {
  // Example
  echo 'unknwon variable found at line '.$line;
}

But I wanted to be able to remove the line = 0 of the function and instead just give it the line without needing to call the function like:

exampleFunction('Name', __LINE__);

And instead call it like:

exampleFunction('Name');

And the __LINE__ variable be passed with it instead of needing to include it. - I tried making the function that was being called look like so:

exampleFunction($varname, __LINE__) {
  // Executed code.
}

Though that also didn't work out, chucking an error.


Solution

  • You can use debug_backtrace method in your exampleFunction to get the caller info with line.

    http://php.net/manual/tr/function.debug-backtrace.php

    Example (copied from php.net)

    <?php
    // /tmp/a.php dosyası
    
    function a_test($str)
    {
        echo "\nHi: $str";
        var_dump(debug_backtrace());
    }
    
    a_test('friend');
    ?>
    
    <?php
    // /tmp/b.php dosyası
    include_once '/tmp/a.php';
    ?>
    

    Which outputs:

    Hi: friend
    array(2) {
    [0]=>
    array(4) {
        ["file"] => string(10) "/tmp/a.php"
        ["line"] => int(10)
        ["function"] => string(6) "a_test"
        ["args"]=>
        array(1) {
          [0] => &string(6) "friend"
        }
    }
    [1]=>
    array(4) {
        ["file"] => string(10) "/tmp/b.php"
        ["line"] => int(2)
        ["args"] =>
        array(1) {
          [0] => string(10) "/tmp/a.php"
        }
        ["function"] => string(12) "include_once"
      }
    }