扩展PHP类时的问题 [英] problems when extending a PHP Class
问题描述
我有2个类(2个文件)
db.class.php
user.class.php
我想使用 db.class.php
中的一些函数:
db.class.php
类DBManager {
/ **所有函数都在这里... * /
}
$ DB = new DBManager();
user.class.php的内容是:
类用户扩展DBManager {
function User(){
}
函数Total($ table){
$ query = $ DB-> Execute(SELECT * FROM $ table);
$ total = $ DB-> NumRows($ query);
return $ total;
}
}
$ User = new User();
当我想使用我的新函数total($ table) :
未定义变量:DB在第14行的..\class\user.class.php中
致命错误:调用成员函数Execute ()在第14行上的.. \class\user.class.php中的非对象上
我的main.php文件中的2个类如:
include'class / db.class.php';
include'class / user.class.php';
编辑1:
相关文章:使用扩展类(PHP)时最好的技巧
解决方案c> $ DB 未在
Total
函数中定义/范围内。
如果$ DB
是类的属性,您需要使用$ this-> DB
来访问它。
更新后更新:
您正在实例化
DBManager
导入全局变量$ DB
。此变量仅在全局范围中的作用域中。它不会在任何其他范围内自动可用,如内部函数。是否用户
从继承DBManager
是完全不相关的,实例化变量$
有一个惰性方法访问
中的变量全局
范围,但我不会在这里提到。正确的方法是将$ DB
实例化为User
的类成员,或者在实例化User
:class User {
protected $ DB =空值;
public function __construct($ DB){
$ this-> DB = $ DB;
}
public function Total(){
$ this-> DB-> ...
}
}
$ b b $ DB = new DBManager();
$ user = new User($ DB);
I have 2 classes (2 files)
db.class.php
user.class.phpI want to use some functions from
db.class.php
:db.class.php
Class DBManager { /** all functions goes here ...*/ } $DB = new DBManager();
The content of user.class.php is:
Class User extends DBManager { function User() { } function Total($table) { $query = $DB->Execute("SELECT * FROM $table"); $total = $DB->NumRows($query); return $total; } } $User = new User();
When I want to use my new function total($table) I get 2 errors:
Undefined variable: DB in ..\class\user.class.php on line 14
Fatal error: Call to a member function Execute() on a non-object in ..\class\user.class.php on line 14
I includes the 2 classes in my main.php file like:
include 'class/db.class.php'; include 'class/user.class.php';
Edit 1:
Related post: best trick when using an extending class (PHP)
解决方案Well, yes,
$DB
is not defined/in scope within theTotal
function.
If$DB
is a property of the class, you'll need to access it with$this->DB
.
Update after update:
You're instantiating the
DBManager
into the global variable$DB
. This variable is only in scope in the global scope. It is not automatically available in any other scope, like inside functions. Whether or notUser
inherits fromDBManager
is completely irrelevant, the instantiated variable$DB
is not in scope inside any function.There's a lazy way to access variables in the
global
scope, but I'm not going to mention that here. The proper way would be to instantiate$DB
as a class member ofUser
or pass it upon instantiatingUser
:class User { protected $DB = null; public function __construct($DB) { $this->DB = $DB; } public function Total() { $this->DB->… } } $DB = new DBManager(); $user = new User($DB);
这篇关于扩展PHP类时的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!