PHP Die问题

4

我有一个快速的问题。假设我这样调用一个方法:

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

我可以让“die”调用一个方法而不是显示文本消息吗?如果可以,怎么做?

6个回答

6
如果你想进行更复杂的操作,例如:使用if语句而不是依赖于短路评估会更好。
if (!mysql_pconnect("server","tator_w","password")) {
    call_a_function();
    //some other stuff
    die(); //if you still want to die
}

这样行吗?mysql_pconnect("server","tator_w","password") 或返回 false; - Señor Reginold Francis
不,return是一种语言结构,不能在表达式中使用。你可以这样做:if (!mysql_pconnect(blah)) { return false; } - Tom Haigh
不确定为什么你想使用 "或返回false",因为在那种情况下,你可以只返回第一个操作数的值... - Peter
Peter的意思是,如果连接失败,mysql_pconnect会返回false。因此,在这种情况下没有必要返回false。 - jared
虽然您可能实际上不想返回该资源,但是您可以执行 'return (bool) mysql_pconnect();' 或 'return !! mysql_pconnect();'。 - Tom Haigh

3

register_shutdown_function()

该函数允许您注册一个在系统退出时调用的函数。然后,您可以简单地使用die()exit()而不带参数来调用您的方法。

(如果您有兴趣,也可以查看set_error_handler(),虽然它与本函数略有不同)


0
为什么不直接放一个返回字符串的函数调用呢?

function myDieFunction()
{
     // do some stuff

     return("I died!");
}

die(myDieFunction());

或者你可以尝试注册关机函数


0

另一种(但不太好的)方法:

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

请注意使用二进制运算符&而不是布尔运算符,以调用所有函数。

很遗憾,PHP没有逗号运算符来处理这种情况。但我想这只会让99%的PHP开发人员感到困惑。 - chaos
@chaos:当然。但这只是为了完整起见。我希望没有人会使用它。 - Gumbo

0

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

如果您无法连接到数据库,则可能需要小心处理该问题,并且您可能希望记录有关出了什么问题以及出了什么问题的位置,以便能够使您的代码更好地避免将来出现问题。

只需快速草拟一种使用异常的方法。

文件 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

0

嗯,不完全是这样,但你只需要这样做

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接