从主类继承变量到扩展类PHP


Inheriting variables from the main class to the extended class PHP

我试图让一个子类(feeds)从主类(控制器)继承一个变量。

我有三个文件。它们看起来如下。

核心文件:

/*  ----------------------------- *
 *  LOAD THE CONTROLLER CLASS NOW *
 *  ----------------------------- */
 require(CORE_PATH . 'controller.php');
 require(CORE_PATH . 'load_controller.php');

控制器类:

<?php
class Controller {
    var $sessions, $a;
    public function __construct() {
        $this->sessions = new Sessions();
        $this->a = 'yo';
    }
}

feed类:

class Feeds extends Controller {
    public function feeds() {
        /* We can load other resources here */
    }
    function index($val) {
        echo $this->a;
    }
}

解决办法:

<?php require(PROTECT);
class Controller {
    protected $variable = "Setting the variable right here works.";
    public function __construct() {
        $this->variable = "Setting it right here will only work for the current object. It's as if variable isn't being set at all when it comes to other classes.";
    }
}

除非您使用PHP4,否则您应该避免使用var声明类成员。使用public, private, protected

在您的情况下,因为您已经使用了var,您的成员变量$a应该可以从子类访问。

你得到任何错误吗?