PHP“无法访问受保护的属性”

4
这是我的第一个面向对象编程程序,请不要生气 :) 问题在于我遇到了以下错误:

无法访问 D:\xampp\htdocs\php\OOP\coder_class.php 第47行中的 Code::$text 受保护属性

该程序简单地对字符串进行编码和解码。我不确定这是否是学习面向对象编程的好例子。
<?php
class Code
{
    // eingabestring
    protected $text;

            public function setText($string)
            {
                $this->text = $string;
            }

            public function getText()
            {
                echo $this->text;
            }
}

class Coder extends Code
{
    //Map for the coder
    private $map = array(
        '/a/' => '1',
        '/e/' => '2',
        '/i/' => '3',
        '/o/' => '4',
        '/u/' => '5');

            // codes the uncoded string
    public function coder() 
    {
        return preg_replace(array_keys($this->map), $this->map, parent::text);      
    }
}

class Decoder extends Code
{
    //Map for the decoder
    private $map = array(
    '/1/' => 'a',
    '/2/' => 'e',
    '/3/' => 'i',
    '/4/' => 'o',
    '/5/' => 'u');

            // decodes the coded string
            public function decoder()
    {
        return preg_replace(array_keys($this->map), $this->map, parent::text);      
    }
}

$text = new code();
    $text -> setText("ImaText");
    $text -> coder();
    $text -> getText();

能有人帮我修复这个问题吗?我是PHP新手。


这条信息非常容易理解。哪一行是第47行? - Álvaro González
1
你需要添加一个方法来获取文本,因为只有类本身才能处理它。例如 public function getText() { return $this->text; } 然后 echo $text->getText(); - Waygood
@LightnessRacesinOrbit 他的问题是什么?受保护的属性是什么?应该如何使用它们?访问受保护的属性的最佳实践是什么?这个问题还在继续。一个带有“Help”的语法错误和代码块并不是一个问题。 - Mike B
@MikeB:我感同身受。 - Lightness Races in Orbit
你的代码中有一个拼写错误。应该使用$this->text而不是parent::text。子类可以访问父类的受保护属性。 - akDeveloper
显示剩余6条评论
2个回答

3

使用:

protected $text;

并且:

echo $text->text;

这就是你遇到错误的原因。 protected 意味着只有 Code 类的后代(即 CoderDecoder)才能访问该属性。如果你想通过 $text->text 访问它,它必须是 public。或者,只需编写一个 getText() 方法;你已经编写了 setter。
顺便说一句: publicprivateprotected 关键字与安全几乎没有任何关系。它们通常旨在强制数据/代码/对象的完整性。

2

相关代码:

class Code
{
    protected $text;
}
$text = new code();
echo $text->text;

该属性不是公共的,因此出现了错误。它的工作方式如广告所述。

1
"getText"方法现在可用。 - Nextar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接