【问题标题】:Infinite recursion in PHP with new self()在 PHP 中使用 new self() 进行无限递归
【发布时间】:2015-04-07 21:08:23
【问题描述】:

我现在有了这个用于字符串的类(类型提示,因为它很有趣):

/**
 * A String class for string type hinting in functions
 */
class string {

    /**
     * The value
     * @var string
     */
    public $string;

    /**
     * makes a string out of a string... georgous..
     * @param string $string
     */
    public function __construct($string) {
        if(!is_string($string)):
            return false;
        endif;
        $this->string = new self($string);
    }

    /**
     * magic toString method ;)
     * @return string
     */
    public function __toString() {
        return $this->string;
    }

    /**
     * Serializer
     * @return array
     */
    public function __sleep() {
        return ['string'];
    }

    /**
     * array maker
     * @return array
     */
    public function toArray() {
        return [$this->string];
    }

    /**
     * split a string
     * @return string[]
     */
    public function splitstr() {
        return explode("", $this->string);
    }
}

当我执行$this->string = new self($string); 时,PHP 应该创建一个永无止境的递归量。这看起来像:

new string("test) {
    $string = new string("test") {
        $string = new string("test") {
            $string = new string("test") ... AND SO ON FOREVER
        }
    }
}

现在我的问题是: 为什么 PHP 在执行此操作时会重置网络连接(PHP 和 Apache2)?

【问题讨论】:

  • 我现在已经在没有 Apache 的情况下对此进行了测试。它工作正常,直到我从 bash 收到内存错误并且 PHP 以 139 结尾。
  • 我只是想知道为什么 PHP 没有捕捉到这样的错误...
  • 实际上xdebug.max_nesting_level 是你得到异常后的深度。但是又一次……为什么?这段代码是废话:D 对不起
  • 我知道,它对任何事情都没有用,但我很高兴找到这个小“错误”...
  • 我认为它可能是正确的错误在于 var_dump'ing 它的一个实例...... xD

标签: php class oop recursion


【解决方案1】:
/**
 * makes a string out of a string... georgous..
 * @param string $string
 */
public function __construct($string) {
    if(!is_string($string)):
        return false;
    endif;
    $this->string = new self($string);
}

无限递归

你可以试试

 !self::$string AND self::$string = new self($string);

但我在这里没有帮助。

首先你为什么要发new self()

查找 PHP 中类的单个实例的含义。这是您在 php 中必须new self() 的唯一必要方式。

您的代码中没有type hinting

class A {
   function typeHintingFunction(string $sting){

   }
}

explode($this->string); 遗漏一个参数

帮一点忙

【讨论】:

  • 我知道单例,我正在使用它们。但是我发现做一些奇怪的事情很有趣,比如在其中无限递归一个类。我正在处理的整个文件有 1200 多行。我想在其他一些类的其他地方使用类型提示。 explode($this->string); 通常只有在我使用 $this->string =$string; 时才有效。原因 explode(); 从字符串中创建一个数组。
  • 对其中的一个类进行无限递归对不起,我不明白?分裂
  • 一个自身拥有无限深度的类。更好?
  • PHPs OOP logic 那是? ,但在你回答之前:eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design 它有一点时间花在对 php 生气或对此过于关注。记住奇怪的东西并保存代码;)
  • 还有很多网站显示了php的奇怪行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 2020-12-22
  • 2021-11-15
  • 2017-02-02
  • 1970-01-01
相关资源
最近更新 更多