[英]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: 简而言之:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.