【问题标题】:php: two objects from the same class work independent of each otherphp:来自同一类的两个对象彼此独立工作
【发布时间】:2011-02-15 12:04:06
【问题描述】:

早上好,

我希望我的控制器中的代码看起来像这样:

<?php
$class = new sanitizeInput()

$string1 = $class -> input($_POST[name]) -> mysql_escape();
$string2 = $class -> input($_POST[age]) -> mysql_escape();

print "
     String1: $string1 <br />
     String2: $string2"
?>

似乎在我的 sanitizeInput 类中,对 $string2 的任何更改都会应用于 $string1。 我可以通过什么方式改变这一点?我希望在类中进行更改,以使我的控制器尽可能易于阅读。

当然,我知道我可以实例化两次,但如果可能的话,我想使用同一个对象。

如果我的班级会很棒:

  • 实例化一次,
  • 设置输入,
  • 告诉 mysql_escape,并将 __toString 返回给 $string1。
  • 设置输入,仅保留 $string2,mysql_escape 并将 __toString 字符串返回到 $string2。

编辑: 这是评论要求的我的完整代码:

$name = $sanitize -> setInput($name) -> stripTags() -> mySql() -> replaceLinks('[ En webadresse ble sensurert her ]') -> trimWhitespace();
$age = $sanitize -> setInput($age) -> stripTags() -> mySql() -> replaceLinks('[ En webadresse ble sensurert her ]') -> trimWhitespace();


class Sanitizer {

    protected $_data;

    public function setInput($input) {
        $this -> _data = $input;
        return $this;
    }


    public function stripTags($array = NULL) {
        if (!is_null($array) and is_array($array)) {
            $allowedTags = implode('', $array);
            $this -> _data = strip_tags($this -> _data, $allowedTags);
        }
        else {
            $this -> _data = strip_tags($this -> _data);
        }
        return $this;
    }

    public function mySql() {
        $this -> _data = mysql_escape_string($this -> _data);
        return $this;
    }

    public function replaceLinks($replacement = NULL) {
        if (is_null($replacement)) {
            $replacement = '[ Potential web-address censored here ]';
        }
        $this -> _data = preg_replace('~[a-z0-9:/._-]+\.(biz|com|edu|gov|info|mil|net|org|as|eu|no|se|uk)[/a-z]{0,}~i', $replacement, $this -> _data);
        return $this;
    }

    public function trimWhitespace() {
        $this -> _data = trim($this -> _data);
        return $this;
    }

    protected function __toString() {
        $str = $this -> _data;
        return $str;
    }
}

感谢您的宝贵时间。

亲切的问候,
马吕斯

【问题讨论】:

标签: php class clone sanitization


【解决方案1】:

$string1$string2 将一直引用同一个对象,直到您尝试将值转换为字符串,因此您所做的任何更改都将应用于这两个字符串。我认为您必须将对象显式转换为字符串以防止这种情况发生,例如

$string1 = (string) $class -> input($_POST['name']) -> mysql_escape();
$string2 = (string) $class -> input($_POST['age']) -> mysql_escape();

我不确定在这里使用“流利”接口是否合适,因为如果您想同时在多个地方使用同一个实例,您并不真的希望对象在调用之间保持状态。最好为每个字符串使用不同的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    相关资源
    最近更新 更多