Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

register_shutdown_function() php

Tags:

php

I am new at php. I came to know about register_shutdown_function() in php. I have read about this function in php.net manual that when script finish execution this function calls. But i have a question

What if i put this function in namespace like

 namespace MyNamespace;
 register_shutdown_function("myHandler");  // this throws an error because it can't find function
 function myHandler() 
 { 
    // Some Code.
 }


 namespace MyNamespace;
 register_shutdown_function("MyNamespace\myHandler");  // this throws no error.
 function myHandler() 
 { 
    // Some Code.
 }

why this happens both register_shutdown_function() and myHandler() are in same namespace??

and if i put this namespace in different file and i include that file but i won't use this namespace 'MyNamespace' then does it execute?

like image 490
Sohil Desai Avatar asked Oct 10 '13 13:10

Sohil Desai


2 Answers

Actually, register_shutdown_function() has nothing to do with that. It's about how PHP parses string callbacks. See this sample:

namespace MyNamespace;
$data = ['foo', 'bar'];
$data = array_filter($data, 'myHandler'); //warning, while 'MyNamespace\myHandler' is ok
register_shutdown_function("MyNamespace\myHandler");
function myHandler() 
{
        return 1;
}

-i.e. you must qualify your callback with it's full path to use that inside string-callbacks. That's because if you're specifying callback as a string, it becomes like global context (i.e. no more related to current namespace context) - because string itself does not contain any references to current namespace scope, it's just a string and nothing more.

like image 55
Alma Do Avatar answered Nov 14 '22 19:11

Alma Do


The shutdown function is probably called after all objects have been deconstructed, have you tried:

May be below code help full to you...

<?php
function shutdown()
{
    // This is our shutdown function, in 
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>
like image 22
Mandip Darji Avatar answered Nov 14 '22 20:11

Mandip Darji