这是我的第一个面向对象程序,所以请不要生我的气:)问题是我得到了以下错误:
无法访问受保护的属性Code::$text in D:'xampp'htdocs'php'OOP'coder_class.php第47行
程序只是对字符串进行编码并解码。我不确定这是否是一个学习OOP的好例子。
<?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的新手。
With:
protected $text;
:
echo $text->text;
是你得到错误的原因。protected
意味着只有Code
类的后代才能访问该属性,即。Coder
和Decoder
。如果你想通过$text->text
访问它,它必须是public
。或者,只写一个getText()
方法;您已经编写了setter。
public
、private
和protected
关键字实际上与安全性没有任何关系。它们通常用于加强数据/代码/对象的完整性。
相关代码:
class Code
{
protected $text;
}
$text = new code();
echo $text->text;
属性不是公共的,因此出现错误。