PHP中的成员和函数继承


Member and Function Inheritance in PHP

我仍然是PHP的新手,我有很多麻烦。我已经习惯了像C、c++和Java这样的语言,但这个有点让我困惑。基本上我的问题是,我有以下代码:

class File_Reader 
{
    protected $text;
    public function Scan_File (){}
    public function Skip_Whitespace(&$current_pos)
    {
        //skip past whitespace at the start
        while (($current_pos < strlen($text) && ($text[$current_pos] == ' ')))
            $current_pos++;
    }
    public function __construct(&$file_text)
    {
        $text = $file_text;
    }
}
class Times_File_Reader extends File_Reader
 {
     Public Function Scan_File()
     {
         $errors = array();
         $times = array();
         $current_time;
         $cursor = 0;
         $line = 0;
         while ($cursor < strlen($text))
         {
             Skip_Whitespace($cursor);
             //....lots more code here...
             return $times;
         }
     }
 }

但是当我尝试运行它时,它告诉我$time和Skip_Whitespace都是未定义的。我不明白,应该是遗传的。我尝试在File_Reader构造函数中放入echo命令,当我创建Times_File_Reader时,它确实会进入构造函数。

哦,为了完整起见,这里是我声明Times_File_Reader的地方:

   include 'File_Readers.php';
  $text = file_get_contents("01_CT.txt");
  $reader = new Times_File_Reader($text);
  $array = $reader->Scan_File();

我已经找了几个小时的答案,但是毫无结果,而最后期限很快就要到了。任何帮助都会很感激。谢谢你!

我相信您需要注意的是,您是通过使用

来使用类函数的

$this->Skip_Whitespace($cursor);

您需要将传递给构造函数的属性设置为类的属性(方法中的变量的作用域与Java相同)。

使用$this->property

// File_Reader
public function __construct(&$file_text)
{
    $this->text = $file_text;
}
// Times_File_Reader
public function Scan_File()
{
    $errors = array();
    $times = array();
    $current_time;
    $cursor = 0;
    $line = 0;
    while ($cursor < strlen($this->text))
    {
        $this->Skip_Whitespace($cursor);
        //....lots more code here...
        return $times;
    }
}

编辑-顺便说一句,你似乎在使用一些古怪的下划线/标题大小写混合。PHP的最佳实践是使用lowerCamelCase表示方法,使用CamelCase表示类名。

class FileReader
class TimesFileReader
public function scanFile()

另外-你通过引用传递变量(&$var) -你可能不必这样做(我能想到的唯一有效的用例是在使用闭包/匿名函数的某些情况下)。我承认医生对此的解释不是很清楚。http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html

public function __construct($file_text)
{
    $this->text = $file_text;
}