Завершить работу функции php

exit

Прекращает выполнение скрипта. Функции отключения и деструкторы объекта будут запущены даже если была вызвана конструкция exit.

exit — это конструкция языка, и она может быть вызвана без круглых скобок если не передается параметр status .

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

Если параметр status задан в виде строки, то эта функция выведет содержимое status перед выходом.

Если параметр status задан в виде целого числа ( integer ), то это значение будет использовано как статус выхода и не будет выведено. Статусы выхода должны быть в диапазоне от 0 до 254, статус выхода 255 зарезервирован PHP и не должен использоваться. Статус выхода 0 используется для успешного завершения программы.

Замечание: PHP >= 4.2.0 НЕ выведет параметр status если он задан как целое число ( integer ).

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

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования exit

$filename = ‘/path/to/data-file’ ;
$file = fopen ( $filename , ‘r’ )
or exit( «Невозможно открыть файл ( $filename )» );

Пример #2 Пример использования exit со статусом выхода

//нормальный выход из программы
exit;
exit();
exit( 0 );

//выход с кодом ошибки
exit( 1 );
exit( 0376 ); //восьмеричный

Пример #3 Функции выключения и деструкторы выполняются независимо

class Foo
public function __destruct ()
echo ‘Деинициализировать: ‘ . __METHOD__ . ‘()’ . PHP_EOL ;
>
>

function shutdown ()
echo ‘Завершить: ‘ . __FUNCTION__ . ‘()’ . PHP_EOL ;
>

$foo = new Foo ();
register_shutdown_function ( ‘shutdown’ );

exit();
echo ‘Эта строка не будет выведена.’ ;
?>

Результат выполнения данного примера:

Завершить: shutdown() Деинициализировать: Foo::__destruct()

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

Замечание:

Эта языковая конструкция эквивалентна функции die() .

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

Источник

Завершить работу функции php

die — Эквивалент функции exit

Описание

Данная функция эквивалентна функции exit() .

User Contributed Notes 8 notes

It is poor design to rely on die() for error handling in a web site because it results in an ugly experience for site users: a broken page and — if they’re lucky — an error message that is no help to them at all. As far as they are concerned, when the page breaks, the whole site might as well be broken.

If you ever want the public to use your site, always design it to handle errors in a way that will allow them to continue using it if possible. If it’s not possible and the site really is broken, make sure that you find out so that you can fix it. die() by itself won’t do either.

If a supermarket freezer breaks down, a customer who wanted to buy a tub of ice cream doesn’t expect to be kicked out of the building.

Beware that when using PHP on the command line, die(«Error») simply prints «Error» to STDOUT and terminates the program with a normal exit code of 0.

If you are looking to follow UNIX conventions for CLI programs, you may consider the following:

fwrite ( STDERR , «An error occurred.\n» );
exit( 1 ); // A response code other than 0 is a failure
?>

In this way, when you pipe STDOUT to a file, you may see error messages in the console and BASH scripts can test for a response code of 0 for success:

rc@adl-dev-01:~$ php die.php > test
An error occurred.
rc@adl-dev-01:~$ echo $?
1

Ideally, PHP would write all Warnings, Fatal Errors, etc on STDERR, but that’s another story.

do_something ( $with_this ) or die ( ‘oops!’ );
?>

(in php, «die» is actually an alias of «exit»)

beware until this is often used as an error handling statement actually isn’t. is just the «or» boolean operator overloaded (short circuited)

it won’t supress any error message, won’t prevent you for fatal errors or crashes, is not an alias for «try/catch», and could has unpredictable results. it just means something like this:

— execute the first statement «»do_something($with_this)»» normally
— if the statement results TRUE: no need to execute the second statement so skip it
— else if returns FALSE. well i am not sure about the result of the whole expression, so continue with second statement «»die(‘cuack!)»»

so you can’t rely on all statements will suppress error messages or crashes, or will always return «false» on error or undesirable behavior.

for this better use the error skipping operator «@» «if» and «exit» commands, or use «try/catch» blocks

die doesn’t prevent destructors from being run, so the script doesn’t exit immediately, it still goes through cleanup routines.

Using die() can be a good option when working with HTTP Endpoints.

If your PHP Script is one, you can use die() to send back an error as plain text or JSON for example.

die(json_encode(array(‘error’ => ‘some error’)));

I always think about why duplicate commands deserve to exist, but die is one of those that I know why. It may be the same as exit(), but when you want to search through source code for die() for an unhandled error vs. a clean exit(), it helps a bit on the debugging. Not to mention backward compatibility, but we deprecate those reasons for ‘good’ reason.

Do not forget to add an error log, so you also get to know about the problem, as well as an error 500 header.

$message = ‘Description of the error.’;
error_log($message);
header($_SERVER[‘SERVER_PROTOCOL’] . ‘ 500 Internal Server Error’, true, 500);
die($message);

The «die» function is good to use when an error occurs and you need to instantly leave, and the «exit» function is good to use when a program is done without any errors. Why that? So you can search dies in the program and debug better.

  • Разные функции
    • connection_​aborted
    • connection_​status
    • constant
    • define
    • defined
    • die
    • eval
    • exit
    • get_​browser
    • _​_​halt_​compiler
    • highlight_​file
    • highlight_​string
    • hrtime
    • ignore_​user_​abort
    • pack
    • php_​strip_​whitespace
    • sapi_​windows_​cp_​conv
    • sapi_​windows_​cp_​get
    • sapi_​windows_​cp_​is_​utf8
    • sapi_​windows_​cp_​set
    • sapi_​windows_​generate_​ctrl_​event
    • sapi_​windows_​set_​ctrl_​handler
    • sapi_​windows_​vt100_​support
    • show_​source
    • sleep
    • sys_​getloadavg
    • time_​nanosleep
    • time_​sleep_​until
    • uniqid
    • unpack
    • usleep

    Источник

    Завершить работу функции php

    return returns program control to the calling module. Execution resumes at the expression following the called module’s invocation.

    If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return also ends the execution of an eval() statement or script file.

    If called from the global scope, then execution of the current script file is ended. If the current script file was include d or require d, then control is passed back to the calling file. Furthermore, if the current script file was include d, then the value given to return will be returned as the value of the include call. If return is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini , then that script file’s execution is ended.

    Note: Note that since return is a language construct and not a function, the parentheses surrounding its argument are not required and their use is discouraged.

    Note: If no parameter is supplied, then the parentheses must be omitted and null will be returned. Calling return with parentheses but with no arguments will result in a parse error.

    As of PHP 7.1.0, return statements without an argument in functions which declare a return type trigger E_COMPILE_ERROR , unless the return type is void , in which case return statements with an argument trigger that error.

    Источник

    PHP: Stop Code Execution with Exit

    How we can use the PHP’s exit function to stop the execution of remaining code.

    d

    Stop running the script with the exit function, PHP

    exit is usually used right after sending final output to a browser, or to stop a script in case there was an error. When exit is used it will stop code-execution completely and exit PHP.

    You should use return when you want to send a value back to the calling location, and exit when you want PHP to stop executing the rest of your script. Here is an example of how to exit a script:

    echo '

    Hallo World

    '
    ; exit(); // Code past this point will not be executed // . more code here

    exit is often used for quick and dirty bug hunting by developers when they want to test output; when this is done, output is usually sent with echo, print, print_r, and var_dump It is probably quite common to have a function to output the content of variables:

    function dumpText($variable)  header('content-type: text/plain; charset=utf-8'); var_dump($variable); exit(); > 

    Another common place to call exit is after sending a location header redirect:

    header('Location: https://beamtic.com/'); exit(); 

    Calling exit from functions and methods

    When a function or method is called, it will usually return to the calling script once it finishes executing the relevant function-code.

    If for example we responding to a HTTP request from within a function, it would often be desired to have the script stop executing any remaining code. I.e.:

    function respond_not_found($code)  http_response_code(404); header('Content-Type: text/html; charset=UTF-8'); echo '

    404 Not Found

    '
    . '

    Eh!? Now you are just guessing.

    '
    ; exit(); >

    Then, when checking the requested page, we can simply output a 404 and exit when the page is not found:

    $valid_system_pages_arr = array('frontpage' => true, 'categories' => true, 'blog' => true); if (isset($valid_system_pages_arr["$requested_page"]) == false)  respond_not_found(); > // The rest of our code goes here :-D echo 'A valid system page was requested.'; 

    Exiting from within loops

    We can not use exit inside a loop, since it would completely stop running the rest of the program. Usually, you would want to just stop executing the rest of the loop, for this we can use the break keyword.

    However, using the break keyword would usually rise the need to use conditional logic inside of the loop, which can be inefficient, depending on the circumstances.

    Using the break keyword to stop a loop from running:

    $i = '1'; while ($number  '15')  break(); // Only the loop stops executing echo 'Run Number:' . $number . "\n"; ++$number; > 
    $i = '1'; while ($number  '15')  exit(); // The program exits on the first run without running any remaining code echo 'Run Number:' . $number . "\n"; ++$number; > // This code will not be executed, since we "exit" the script inside the loop 

    Variable-dumping

    Variable-dumping works well for learning the structure of a variable’s contents, this is also commonly done when debugging and bug hunting — but as an application grows you will probably want more sophisticated error handling.

    Often, when PHP developers are debugging applications, they will be using var_dump and print_r in combination with exit to output the content of variables and objects. This can be practiced from anywhere within a script, even from methods in a Object Orientated application.

    An example of this would be:

    $my_array = array('bug', 'hunt', 'professionals'); $some_variable = 'test'; var_dump($some_variable); print_r($my_array); exit(); 

    It is easier to have a function declared somewhere in the global scope:

    function dumpHTML($variable)  header('content-type: text/html; charset=utf-8'); var_dump($variable); exit(); > 

    Источник

    Читайте также:  Структура базы данных java
Оцените статью