PHP来自孩子的私有变量访问

iLo*_*och 6 php oop private class protected

所以我正在尝试解决我在设计PHP类时遇到的问题.我已经创建了一个基类,并分配了私有变量.我有扩展这个基类的子类,它通过基类的函数对这些私有变量进行引用和更改.下面是一个例子,记住我仍然感到困惑之间的区别privateprotected方法/变量(让我知道如果我做错了!):

base.class.php

<?php
class Base {
    private $test;
    public function __construct(){
        require('sub.class.php');
        $sub = new Sub;
        echo($this->getTest());
    }
    public function getTest(){
        return $this->test;
    }
    protected function setTest($value){
        $this->test = $value;
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

sub.class.php

<?php
class Sub extends Base {
    public function __construct(){
        parent::setTest('hello!');
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

所以我希望将结果hello!打印在屏幕上 - 而不是什么都没有.我可能会对课程产生根本性的误解,或者我可能只是做错了什么.非常感谢任何指导!谢谢.

编辑:

感谢所有提供答案的人 - 我认为,尽管有很好的解决方案,但是这些子类实际上并不是我需要的 - 似乎委托类在这一点上可能更有用,因为我真的不需要引用Base其他类中的函数.

flo*_*ree 8

应该是这样的:

base.class.php:

class Base {
    private $test;
    public function __construct() {
        echo $this->getTest();
    }
    public function getTest() {
        return $this->test;
    }
    protected function setTest($value) {
        $this->test = $value;
    }
}
Run Code Online (Sandbox Code Playgroud)

sub.class.php:

class Sub extends Base {
    public function __construct() {
        parent::setTest('hello!');  // Or, $this->setTest('hello!');
        parent::__construct();
    }
}
Run Code Online (Sandbox Code Playgroud)

主要代码:

require 'base.class.php';
require 'sub.class.php';

$sub = new Sub;  // Will print: hello!
Run Code Online (Sandbox Code Playgroud)

  • 我也会用`$ this->`替换`parent ::` (2认同)