只是一个简单的问题。说的呼叫,像这样的方法

mysql_pconnect("server","tator_w","password")
               or die("Unable to connect to SQL server");

我可以有“死”调用方法而不是显示文本消息?如果是的话,如何?

有帮助吗?

解决方案

如果你想做的任何事情更复杂,e.g你会过得更好使用if语句,而不是依赖于短路评价:

if (!mysql_pconnect("server","tator_w","password")) {
    call_a_function();
    //some other stuff
    die(); //if you still want to die
}

其他提示

register_shutdown_function()

它可以让你注册将被调用的系统退出时功能。然后,你可以简单地die()exit()不带参数,这将调用你的方法。

(你也可以找到的set_error_han dler()有趣如果稍有不相关的)

好了,不完全是,但你只是做

if(!mysql_pconnect("server","tator_w","password")) {
    $some_obj->some_method();
    exit(1);
}

为什么不只是把一个函数调用返回一个字符串?


function myDieFunction()
{
     // do some stuff

     return("I died!");
}

die(myDieFunction());

或者你可以尝试href="http://us.php.net/manual/en/function.register-shutdown-function.php" rel="nofollow noreferrer">注册关机功能

另一个(但不是很好)的方法:

mysql_pconnect("server","tator_w","password")
    or foo() & bar() & die("Unable to connect to SQL server");

请注意的二进制运算符&代替一个布尔操作员具有所有调用的函数。

不能够连接到数据库可能是一个严重的问题 - 我认为它的使用异常的主要目标

如果您无法连接到该问题可能需要进行细致处理的数据库,你可能想记录一些关于什么地方出了错,以及哪里出了问题才能够让你的代码更好地避免问题在未来。

只是一个速写了一种方法来使用异常。

文件view_cart.php

<?php
try
{
    require_once('bootstrap.php');
    require_once('cart.php');

    require('header.php');


    // Get the items in the cart from database
    $items = Cart::getItems();

    // Display them to the user
    foreach ($items as $item)
    {
        echo $item->name.', '$item->price.'<br />';
    }
}
catch (Exception $e)
{
    // Log the exception, it will contain useful info like
    // the call stack (functions run, paramaters sent to them etc)
    Log::LogException($e);

    // Tell the user something nice about what happened
    header('Location: technical_problem.html');
}

require('footer.php');

文件bootstrap.php中

<?php
$result = mysql_pconnect("server", "tator_w", "password");
if ($result === false)
{
    throw new Exception('Failed to connect to database');
}

// Select database
// Setup user session
// Etc
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top