简体   繁体   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

The code is working , but as there is no properties of the class are set which is a bad practice, which variables of this code should be set as a class property and why? 该代码正在运行,但是由于没有设置类的属性,这是一种不好的做法,因此应将此代码的哪些变量设置为类属性,为什么?

It's not necessarily bad practice if the above code is ALL you plan on doing with this code. 如果上面的代码是您打算使用此代码完成的所有代码,那么这不一定是不好的做法。 If you needed to expand its functionality, I might imagine $editingtext could be a property. 如果您需要扩展其功能,我可能会认为$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

There are other things wrong with your code, and it is not the absence of properties. 您的代码还有其他问题,这不是缺少属性。 You are constructing an object and in the constructor you output the result. 您正在构造一个对象,然后在构造函数中输出结果。 THAT is bad practice. 不好的做法。

I'd fix it something like this: 我将修复以下问题:

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

then call like: 然后像这样打电话:

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

In short: 简而言之:

  1. Nothing wrong with not using properties, if your class is designed like that. 如果您的类是这样设计的,那么不使用属性也没错。
  2. Please use useful class, method and variable names. 请使用有用的类,方法和变量名。
  3. Don't do more than one thing in a method ("side effects"). 在一种方法中不要做太多事情(“副作用”)。
  4. Don't output the result, but return it. 不输出结果,而是返回结果。 It is up to the user of the class to decide what happens to the results. 由班级用户决定结果如何处理。
  5. (most importantly): Think before you code. (最重要的是):在编写代码之前请三思。

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

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