Getting the calling function name in a debug message with PHP

Published on 2022-09-22 • Modified on 2022-09-22

This snippet shows how to get the calling function name in a debug message with PHP. That's a common need when you want to log or print a helpful debug message to give more context. The two arguments of the debug_backtrace() function are essential; otherwise we get the whole script trace with objects.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use function Symfony\Component\String\u;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet220Trait
{
    public function snippet220(): void
    {
        $dbg = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        $file = u($dbg[0]['file'] ?? '')->after('strangebuzz.com')->toString(); // only keep the root project path
        $line = $dbg[0]['line'] ?? '';
        $function = $dbg[1]['function'] ?? '';
        $class = $dbg[1]['class'] ?? '';

        echo "This function was called by $class::$function() at line $line (from file $file).";

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!