4

只是一个快速的问题。说一个这样的方法

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

我可以让“死”调用一个方法而不是显示一条短信吗?如果是这样,怎么做?

4

6 回答 6

6

如果您想做更复杂的事情,最好使用 if 语句而不是依赖短路评估,例如:

if (!mysql_pconnect("server","tator_w","password")) {
    call_a_function();
    //some other stuff
    die(); //if you still want to die
}
于 2009-07-02T14:16:33.557 回答
3

register_shutdown_function()

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

(您可能还会发现set_error_handler()很有趣,如果稍微无关的话)

于 2009-07-02T14:31:46.943 回答
0

好吧,不完全是,但你只是这样做

if(!mysql_pconnect("server","tator_w","password")) {
    $some_obj->some_method();
    exit(1);
}
于 2009-07-02T14:17:13.820 回答
0

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


function myDieFunction()
{
     // do some stuff

     return("I died!");
}

die(myDieFunction());

或者您可以尝试注册关闭功能

于 2009-07-02T14:19:29.340 回答
0

另一种(但不是很好)方式:

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

请注意使用二元运算符&而不是布尔运算符来调用所有函数。

于 2009-07-02T14:20:29.790 回答
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
于 2009-07-02T20:05:19.380 回答