【问题标题】:Class Variables Not Staying Set (PHP)类变量未设置 (PHP)
【发布时间】:2012-04-11 19:55:40
【问题描述】:

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

函数导入如下所示:

<?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 类时没有收到任何错误,所以我知道它确实包括我的文件。

【问题讨论】:

    标签: php class variables include global


    【解决方案1】:

    这里发生的情况是,在您的类方法中,您获取和设置局部变量 ($buffer) 而不是访问属性 ($this-&gt;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;
    }
    

    【讨论】:

    • 好的,我知道了。我不得不这样做 $this->buffer = "String";设置缓冲区变量并获取它。这似乎对我有用。
    【解决方案2】:

    我认为你的课应该是

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

    通过这种方式,您正在设置一个类变量,而您的代码只是在方法中设置变量

    【讨论】:

      猜你喜欢
      • 2019-07-25
      • 2018-05-08
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      相关资源
      最近更新 更多