我有一个使用一些功能元素和一些OOP元素的php项目,但似乎将两者混合在一起会导致问题。以下是导致错误的文件:
数据库.php
<?php
function parse_db_entry($from, &$to){
//Function code here
}
?>
用户.php
<?php
require_once 'DB.php';
class User{
//Properties
public function __construct(){
//ctor
}
public static function load_user($email, $password){
$entry = //Make MySQL Request
$user = new User();
parse_db_entry($entry, $user);
return $user;
}
}
?>
一切都按预期工作,除了对 parse_db_entry
的调用,它抛出:
致命错误:调用未定义的函数 parse_db_entry()
我能够在 DB.php 中访问其他内容,例如,如果我在那里创建了一个类,我就可以毫无错误地实例化它,如果我将函数移动到 User.php,它也是函数的。那我做错了什么呢?为什么我不能调用此方法?
我已经想通了!感谢所有有想法的人,但问题似乎出在别的什么地方。
当调用require_once 'DB.php'
时,php实际上正在获取文件:
C:''xampp''php''pear''DB.php
而不是我的。
这可能是 XAMPP 独有的问题,但只需重命名我的文件即可DBUtil.php
修复所有内容。
这是一个延伸,我完全是在黑暗中拍摄,但是......
您确定parse_db_entry
在全局或用户的命名空间中吗?注意:我在这里和那里添加了几行用于测试/调试。
数据库.php:
<?php
namespace anotherWorld; // added this ns for illustrative purposes
function parse_db_entry($from, &$to){
echo 'called it';
}
?>
用户.php:
<?php
namespace helloWorld; // added this ns for illustrative purposes
class User {
//Properties
public function __construct(){
//ctor
}
public static function load_user($email, $password){
$entry = //Make MySQL Request
$user = new User();
parse_db_entry($entry, $user);
return $user;
}
}
?>
测试.php:
<?php
require_once 'DB.php';
require_once 'User.php';
use helloWorld'User;
$a = new User();
$a->load_user('email','pass');
echo 'complete';
?>
产生Fatal error: Call to undefined function helloWorld'parse_db_entry() in User.php on line 13
,但是当删除DB中的NS声明时.php(namespace anotherWorld
),从而将parse_db_entry
放入全局NS中,它运行良好。
若要验证,请使用__NAMESPACE__
常量。
如果命名空间是一个问题,在不影响数据库命名空间的情况下,下面是一个更新的用户.php:
<?php
namespace helloWorld;
use anotherWorld; // bring in the other NS
class User {
//Properties
public function __construct(){
//ctor
}
public static function load_user($email, $password){
$entry = //Make MySQL Request
$user = new User();
anotherWorld'parse_db_entry($entry, $user); // call the method from that NS
return $user;
}
}
?>