2013-04-11 49 views
1

我还是PHP新手,遇到很多麻烦。我习惯于像C,C++和Java这样的语言,而这个有点令我困惑。基本上我的问题是,我有以下代码:PHP中的成员和函数继承

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; 
     } 
    } 
} 

但是当我尝试运行它,它告诉我,$时间和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(); 

我一直在寻找了几个小时的答案无济于事,而且期限正在迅速接近。任何帮助,将不胜感激。谢谢!

回答

1

您需要将您传递给构造函数的属性设置为该类的属性(方法内的变量的范围与Java相同)。

你做到这一点使用这个 - $>属性

// 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; 
    } 
} 

编辑 - 顺便说一句,你似乎可以用一些古怪的underscorecase /标题字符的混合体。 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; 
} 
+0

好注意,您所使用的类函数,这是帮助。谢谢!但是,我仍然不能使用Skip_Whitespace($ cursor); 它给我的错误是: 致命错误:调用在C未定义功能Skip_Whitespace():\ XAMPP \ htdocs中\软件工程\ File_Readers.php上线58 任何线索为什么这部分不加工? –

+0

再次 - 您需要使用$ this-> method()。相应地更新了代码。 – calumbrodie

+0

好的。谢谢。另外,就“古怪的下划线/ Titlecase混合”而言,那不是我的选择。队长因为某种原因不喜欢骆驼案件,并拒绝让它成为我们编码标准的一部分。 :\ –

2

我相信,你需要使用

$this->Skip_Whitespace($cursor);

+1

它不仅仅是'$ this-> Skip_Whitespace($ cursor)';'你还需要使用'$ this-> text'作为下一个答案的建议。 –

+0

@PhillSparks你是对的。当我认为他的意思是$文本时,我对他提到的$时间感到困惑。 –