1
$someClass sc=new SomeClass();

我想知道的是,如果构造函数由于某种原因失败(比如可能没有足够的内存),变量 sc 中的内容是什么。我找不到直接的答案?

4

4 回答 4

3

With your example of memory issue, You get a fatal error and php ceases execution. You never get to the assignment of the varible $sc.

于 2012-09-28T14:46:19.197 回答
2

构造函数失败主要有两个原因:

  1. 记不清; 不是对象独有的,这会导致致命错误并且您的脚本将无法继续。

  2. 抛出异常;除非使用“try-catch”子句捕获异常,否则您的脚本将停止。

try {
    $sc = new SomeClass(); // exception is thrown inside the constructor
} catch (Exception $e) {
    echo "Yikes, object didn't get created; error = {$e->getMessage()}\n";
}
于 2012-09-28T14:50:36.940 回答
0

first of all, the syntax for object initiation is incorrect, needs to be $sc = new SomeClass(); And you would get an memory exhaustion error, and variable $sc wouldn't be created.

于 2012-09-28T14:46:46.433 回答
0

当任何其他类型的代码由于某种原因(例如内存不足等)失败时也会发生同样的事情:PHP 运行时发出一个致命错误,仅此而已。对象构造函数并不特殊。

于 2012-09-28T14:47:57.807 回答