![](/img/trans.png)
[英]How the Class file is including in another file php using the namesapce and Use?
[英]How call RuntimeException using namesapce in php version 5.5.8
我正在嘗試使用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;
}
}
?>
在其他類文件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()
作為標准答案,請檢查您的PHP版本。 RuntimeException
的文檔至少需要PHP 5.1或更高版本。
您可以通過控制台中的phpinfo()
或php -v
來執行此操作(如果您在本地運行它並可以通過PATH訪問php)
編輯: 這個問題和答案似乎有關 。 本質上,它也是導致混淆的名稱空間。 本質上,它正在尋找具有名稱空間的RuntimeException類(請參見錯誤)。
由於您使用的是名稱空間,因此您每次使用本機類時都需要引用回根名稱空間( \\
)。
您可能要嘗試:
throw new \RuntimeException('...'); // The '\' tells PHP to use the root namespace.
第二次編輯:
至於第二個問題,這與代碼順序有關。 在CallerNS.php
文件中,您聲明使用命名空間Pack\\sp
, 然后將命名空間文件包含在代碼中。 這將行不通,因為您必須先聲明名稱空間才能使用它。
您可以先包含文件,也可以使用\\Pack\\sp\\Funct0(...)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.