2012-03-28 46 views
1

好的,我不确定100%这里发生了什么,但我认为它与我试图包含一个类使用PHP的“包括( $文件)“功能。类别变量不停留设置(PHP)

功能导入看起来是这样的:

<?php 
function import($file) { 
    global $imported; $imported = true; 
    $home_dir = "C:/xampp/htdocs/includes/"; 
    if (file_exists($home_dir.$file.".php")) { 
     include_once($home_dir.$file.".php"); 
     } 
    $imported = false; 
    } 
?> 

我要做的就是调用下面的PHP在我的index.php文件:

<?php 
import("php.buffer"); 

$out = new StringBuffer; 
$out->write("test?"); 
echo "'".($out->get())."' &lt;- Buffer String Should Be Here"; 
?> 

的php.buffer.php文件看起来像这样:

<?php 
class StringBuffer { 
    public $buffer = ""; 

    public function set($string) { 
     if (!isset($buffer)) { $buffer = ""; } 
     $buffer = $string; 
     } 

    public function get() { 
     if (!isset($buffer)) { $buffer = ""; } 
     return $buffer; 
     } 

    public function write($string) { 
     if (!isset($buffer)) { $buffer = ""; } 
     $buffer = $buffer.chr(strlen($string)).$string; 
     } 

    public function read() { 
     if (!isset($buffer)) { $buffer = ""; } 
     $return = ""; 
     $str_len = substr($buffer,0,1); $buffer = substr($buffer,1,strlen($buffer)-1); 
     $return = substr($buffer,0,$str_len); $buffer = substr($buffer,$str_len,strlen($buffer)-$str_len); 

     return $return; 
     } 

    public function clear() { 
     $buffer = ""; 
     } 

    public function flushall() { 
     echo $buffer; 
     $this->clear(); 
     } 

    public function close() { 
     return new NoMethods(); 
     } 
    } 
?> 

当我创建新的StringBuffer类我没有得到任何错误,所以我知道它确实是我包括我的文件。

+0

你面临什么问题? – 2012-03-28 08:41:10

回答

2

这里发生的是在你的类方法中,而不是访问你正在获取的属性($this->buffer),并设置局部变量($buffer),所以变化不会“粘住”。

该代码也可以使用一些清理。有很多多余的东西在里面,例如:

public function set($string) { 
    // isset will never return false, so this if will never execute 
    // even if it did, what's the purpose of setting the buffer when you 
    // are going to overwrite it one line of code later? 
    if (!isset($this->buffer)) { $this->buffer = ""; } 
    $this->buffer = $string; 
} 
+0

好吧,我明白了。我不得不做$ this-> buffer =“String”;设置缓冲区变量并获取它。这现在似乎适用于我。 – 2012-03-28 08:53:40

1

我认为你的类应该是

class StringBuffer { 
    private $buffer = ""; 

    public function get() { 
     if (!isset($this->$buffer)) { $this->$buffer = ""; } 
     return $this->$buffer; 
     } 

    public function write($string) { 
     if (!isset($this->$buffer)) { $this->$buffer = ""; } 
     $this->$buffer = $this->$buffer.chr(strlen($string)).$string; 
     } 
} 
这样你要设置一个类变量

,与你的代码只是设置变量内部方法