类变量不停留(PHP)

时间:2012-03-28 08:36:27

标签: php class variables include global

好吧,我不确定100%这里发生了什么,但我认为这与我试图使用php的“include($ file)”函数包含一个类的事实有关。

函数import看起来像这样:

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

我所做的就是在index.php文件中调用以下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类时,我没有遇到任何错误,因此我知道它确实包含了我的文件。

2 个答案:

答案 0 :(得分:2)

这里发生的是在您的类方法中,而不是访问属性($this->buffer),而不是访问属性($buffer),因此更改不会“粘住”。 / p>

该代码也可以使用一些清理工具。那里有许多冗余的东西,例如:

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

答案 1 :(得分: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;
        }
}

这样你就是设置一个类变量,你的代码就是在方法

中设置变量