在 php 中,哪些变量应该设置为类的属性


Which variables should be set as the properties of a class in php?

<?php
class oopClass{
    function __construct($editingtext, $searchfor, $replacewith){
        if(!empty($editingtext) && !empty($searchfor) && !empty($replacewith)){
           $editingtext = str_replace($searchfor,$replacewith,$editingtext);
           echo $editingtext;
        }else{
          echo 'All Fields Are Required.';
        }
    }
}
//closing php

代码正在工作,但是由于没有设置类的属性,这是一种不好的做法,因此应将此代码的哪些变量设置为类属性,为什么?

你的代码还有其他问题,这不是缺少属性。您正在构造一个对象,并在构造函数中输出结果。这是不好的做法。

我会像这样修复它:

class TextReplacer {
    var $search;
    var $replace;
    function __construct($s, $r) {
         $this->search = $s;
         $this->replace = $r;
    }
    function replace($text) {
        // your code, using the properties for search and replace, RETURNING the result
        return $ret;
    }
}

然后像这样调用:

$oo = new TextReplacer("bar", "baz");
echo $oo->replace("let's replace some bars in here");

总之:

  1. 不使用属性并没有错,如果你的类是这样设计的。
  2. 请使用有用的类、方法和变量名称。
  3. 不要在一个方法中做多件事("副作用"(。
  4. 不要输出结果,而是返回它。由类的用户决定结果会发生什么。
  5. (最重要的是(:在编码之前三思而后行。

如果上面的代码是你计划用这段代码做的全部,这不一定是不好的做法。如果您需要扩展其功能,我可能会想象$editingtext可能是一个属性。

class oopClass{
    private $editingtext;        
    function __construct($editingtext, $searchfor, $replacewith){
        $this->editingtext = $editingtext;                
        if(!empty($this->editingtext) && !empty($searchfor) && !empty($replacewith)){
           $this->editingtext = str_replace($searchfor,$replacewith,$this->editingtext);
           echo $this->editingtext;
        }else{
          echo 'All Fields Are Required.';
        }
    }
}
//closing php