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