如何在php 5.5.8版中使用命名空间调用RuntimeException

时间:2014-03-01 02:00:27

标签: php class runtimeexception

我正在尝试使用 RuntimeException

http://www.php.net/manual/en/class.runtimeexception.php

我将这些文件放在同一个文件夹中:

OtherFunctions.php

<?php
namespace Pack\sp;
$Tble = NULL;

function SetTble($tble) {
  global $Tble;
  $Tble = $tble;
}

function GetTble() {
  global $Tble;
  return $Tble;
}

function Funct0($Str0, $Str1) {
  return $Str0 == $Str1;
}

function Funct1($Arg) {
  return "The Value is ".$Arg;
}
//... from 0 to 16
function Funct16($Arg) {
  return "The Value is ".$Arg;
}
?>

如何调用此文件中包含的所有功能?

在一个类File SubClass.php 中我有:

<?php
namespace Pack\sp;
class SubClass {
  public $CArg = "";
  function FnClass($Arg) {
    return "FnClass:The Value is from SubClass".$Arg;
  }
}
?>

在其他类File LeadClass.php 中 我有这个:

<?php
namespace Pack\sp;
require_once("OtherFunctions.php");
require_once("SubClass.php");
class LeadClass {
  public function __construct($Name) {
    echo("_._<br>");
    $NewSC = new SubClass();
    $NewSC->CArg = $Name;
    SetTble($Name);
    echo("ini:GetTble():".GetTble().":end<br>");
    echo("ini:".$NewSC->FnClass($Name).":end<br>");
  }
  public function getName() {
    throw new RuntimeException("Error Ever !<br>");
  }
}
?>

使用所有代码 CallerNS.php

<?php
namespace Pack\sp;
require_once("LeadClass.php");
require_once("OtherFunctions.php");
$NewSC = new LeadClass("first");
$NewSC->getName();
if (Funct0("strings", "strings")) {
  print("same strings<br>");
}
?>

这是我的错误:

致命错误:在第15行的C:... \ LeadClass.php中找不到“Pack \ sp \ RuntimeException”类

在其他版本的 CallerNS.php

<?php
use Pack\sp;
require_once("LeadClass.php");
require_once("OtherFunctions.php");
if (Funct0("strings", "strings")) {
  print("same strings<br>");
}
$NewSC = new LeadClass("first");
$NewSC->getName();
?>

错误消息:

致命错误:在第5行调用C:... \ CallerNS.php中的未定义函数Funct0()

1 个答案:

答案 0 :(得分:2)

作为标准答案,请检查您的PHP版本。 RuntimeException的文档要求至少 PHP 5.1或更高版本。

您可以通过控制台中的phpinfo()php -v执行此操作(如果您在本地运行并且可以通过.PATH访问php)

修改:This question and answer seem related。从本质上讲,它也是导致混淆的命名空间。本质上,它正在寻找一个命名空间的RuntimeException类(请参阅您的错误)。

由于您正在使用名称空间,因此只要您想使用本机类,就需要引用回根名称空间(\)。

您可能想尝试:

throw new \RuntimeException('...'); // The '\' tells PHP to use the root namespace.

第二次编辑:

关于你的第二个问题,这是你的代码顺序问题。 在您的CallerNS.php文件中,您声明要将命名空间Pack\sp然后(包括您的命名空间文件)用于您的代码中。这不起作用,因为在使用它之前需要先声明命名空间。

您可以先包含文件,也可以改用\Pack\sp\Funct0(...)