我有一个主类“main”,我用它来存储配置和一些对象。但是,我无法访问对象&通过$this
扩展main的类中的变量。
以下是我的主要课程:
<?php
class main{
// the configuration vars
public $config = array();
// the current user variables
public $uid; // contains the user ID
public $gid; // contains the group ID
// database variables
public $DB; // contains the connection
public $query_id; // contains the query ID
public $query_count; // how many queries have there been?
// cache variables
public $cache;
// start up functions
public function startup(){
// first, set up the caching
if(function_exists('memcache_connect') AND $this->config['use_memcache'] == true){
// start up memcache
require_once('memcache.class.php');
$this->cache = Cache::getInstance();
}
// now, set up the DB
$this->connectToDatabase();
// now, set up the user session
$this->setUserSession();
// are we logged in? If so, update our location
if($this->uid > 0){
// update location
$this->updateUserSession();
}
}
以下是另一个类
的示例<?php
class user extends main{
public function viewProfile($uid){
exit($this->config['session_prefix']); // displays nothing
if($this->cache->exists('key')){ // fails
$ config值已正确设置,我可以在main
内阅读,但不能在任何子类中阅读。
$ cache-&gt; exists对象只会生成Call to a member function exists() on a non-object
。
在index.php上,加载并设置类。首先设置Main类,然后调用启动函数。配置数组在调用启动之前传递。
有人可以建议我如何解决这个问题吗?
答案 0 :(得分:0)
您可以使用parent::
来引用父类中的变量。
parent::cache->exists('key')
答案 1 :(得分:0)
您确定阵列设置正确吗?
这个简单的测试对我有用:
<?
class main {
public $test = "Woot";
}
class test extends main {
public function __construct() {
echo $this->test;
}
}
$t = new test();
仅出于测试目的,在我的示例中添加一个变量$ test到类main,并尝试在用户构造函数中回显它。
我会检查你的缓存是否真的设置正确。 错误可能在if语句中:
if(function_exists('memcache_connect') AND $this->config['use_memcache'] == true){
这两个条件中的一个未满足,因此您的$ cache变量不会被初始化。
答案 2 :(得分:0)
您可以通过$ this-&gt;属性访问父类的属性,因此问题应该是您没有调用父级的构造函数...
就像这段代码完美无缺:
<?php
class foo {
public $x="aa";
}
class bar extends foo {
public function barbar()
{
echo $this->x;
}
}
$b = new bar;
$b->barbar();
?>
虽然您也可以通过Parent :: attr()
访问父类属性