繁体   English   中英

哪些变量应设置为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

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

如果上面的代码是您打算使用此代码完成的所有代码,那么这不一定是不好的做法。 如果您需要扩展其功能,我可能会认为$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

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

我将修复以下问题:

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. (最重要的是):在编写代码之前请三思。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM