【发布时间】:2018-08-09 18:38:00
【问题描述】:
更新:我为该类编辑了下面的代码,以更正运行它时出现的错误(需要“新”来创建对象)。通过该更正,代码运行并正确生成 HTML。但由于我是 OOP 新手,我仍然想知道我是否采取了正确的方法。
第二次更新:我在下面的附录中解决了对这种技术效率的担忧。我还更正了 URL 中的锚点名称和查询字符串的顺序,它们由 hLink() 正确处理。
我有一个为超链接生成 HTML 的函数。它的参数可能是字符串文字或从数据库中读取的变量。对该函数的示例调用如下所示:
hLink('http://example.com', 'website', 'section', 'input=0', '_blank');
返回:
'<a HRef="http://example.com?input=0#section" target="_blank">website</a>'
第一个参数是必需的,其余四个有默认值。
我正在考虑用类中定义的方法替换此函数,因此函数调用将替换为对该方法的调用,该方法调用对类构造函数的调用。我是面向对象编程的新手,所以我想知道我这样做是否正确,或者我是否应该这样做。
我想出的课程是:
class link
{private $sURL;
private $sText = '';
private $sLocn = '';
private $sQuery = '';
private $sWindow = '';
public function __construct($sURL)
{$this->sURL = $sURL;}
public function sText($sText) {$this->sText = $sText; return $this;}
public function sLocn($sLocn) {$this->sLocn = $sLocn; return $this;}
public function sQuery($sQuery) {$this->sQuery = $sQuery; return $this;}
public function sWindow($sWindow) {$this->sWindow = $sWindow; return $this;}
public function hLink()
{...}
}
其中方法 hLink() 的主体与原始函数 hLink() 的主体相同。
有了这个类,上面的函数调用相当于:
(new link('http://example.com'))->sText('website')->sLocn('section')->sQuery('input=0')->sWindow('_blank')->hLink()
它旨在生成与以前相同的字符串:
'<a HRef="http://example.com?input=0#section" target="_blank">website</a>'
这看起来怎么样?我在正确的轨道上吗?
附录
让我感到困扰的是,上述技术为页面上的每个链接创建了一个新对象,而该对象在使用一次为链接创建 HTML 之后什么也不做。它是一个小对象,一个页面上不会超过几百个,因此不会造成很大的内存负担,但仍然显得浪费和低效。我有一个解决这个问题的想法:
- 在类中,没有构造函数,并且有一个方法 clear() 将所有属性的值设置为其默认值(空)。
- 创建一个此类的实例。
- 使用该对象在页面上放置一个链接,调用其上的 clear() 方法,然后设置所需的任何属性值的方法,最后像以前一样调用输出方法 hLink()。
代码如下:(请原谅我的格式。我知道这不合常规,但我觉得这更容易阅读。)
<?php declare(strict_types = 1);
$oLink = new link;
class link
{private $sURL;
private $sText;
private $sAnchor;
private $sQuery;
private $sWindow;
public function clear()
{$this->sURL = '';
$this->sText = '';
$this->sAnchor = '';
$this->sQuery = '';
$this->sWindow = '';
return $this;
}
public function URL(string $sURL) {$this->sURL = $sURL; return $this;}
public function text(string $sText) {$this->sText = $sText; return $this;}
public function anchor(string $sAnchor) {$this->sAnchor = $sAnchor; return $this;}
public function query(string $sQuery) {$this->sQuery = $sQuery; return $this;}
public function window(string $sWindow) {$this->sWindow = $sWindow; return $this;}
public function hLink()
{return('<a HRef="' . $this->sURL .
($this->sQuery == '' ? '' : '?' . $this->sQuery) .
($this->sAnchor == '' ? '' : '#' . $this->sAnchor) .
'"' . ($this->sWindow == '' ? '' : ' target="' . $this->sWindow . '"') .
'>' . $this->sText. '</a>');
}
}
echo('Link to ' . $oLink->clear()->URL('http://example.com')->text('website')->anchor('section')->query('input=0')->window('_blank')->hLink() . ' in text');
我已经将上述代码作为独立脚本进行了测试,它确实输出了预期的结果:
Link to <a HRef="http://example.com?input=0#section" target="_blank">website</a> in text
那么这是更好的方法吗?现在,每次页面上需要另一个链接时,只有一个对象可以重用。这是为嵌入在 PHP 中的文本中的超链接生成 HTML 的最佳方式吗?
【问题讨论】:
-
这里的逻辑看起来不错,但我建议不要使用像
sLocn这样的快捷方法名称。另一方面,代码格式... -
这在CodeReview 上可能会更好。