我正在做一个游戏的粉丝网站,我想要显示项目的工具提示。我使用Bootstrap工具提示来生成它们。到目前为止,我一直在用数组存储数据的项目做工具提示,然后用BS工具提示显示它。现在,我想要过渡到OOP,并且我想创建类。我在类中使用方法来生成工具提示。然而,我在调用这个方法时遇到了一个真正的问题。让我给你举个例子。
当前方法:
// General variables
$rune_item_level = "<span class='white-tooltip'>Item Level: 1<br>";
$inserted_into_sockets = "Can be inserted into socketed items<br><br>";
$rune_class = "class='rune-image'";
// El Rune
$el_stats = [
"Weapons" => "+50 To Attack Rating, +1 to Light Radius",
"Armor" => "+15 Defense, +1 to Light Radius",
"Helms" => "+15 Defense, +1 to Light Radius",
"Shields" => "+15 Defense, +1 to Light Radius"
];
$el_rune_tooltip = "<span class='rune-tooltip'>El Rune</span><br>";
$el_rune_tooltip .= $rune_item_level;
$el_rune_tooltip .= $inserted_into_sockets;
foreach ($el_stats as $key=>$value){
$el_rune_tooltip.= "<span class='white-tooltip'>" . $key . ": " . $value . "</span>";
$el_rune_tooltip.= "<br>";
}
$el_rune_tooltip .= "<br><span class='white-tooltip'>Required Level 11";
$el_rune = '<img ' . $rune_class . ' src="/images/runes/El_Rune.png" data-toggle="tooltip" data-html="true" title="' . $el_rune_tooltip . '" />';它工作得很好。我将整个工具提示存储到$el_rune变量中,并随时随地调用。
因此,为了过渡到OOP,我执行了以下操作:创建一个Rune类,传递一些属性,然后使用一个名为createTooltip()的函数来创建工具提示。这样,在游戏中创建所有30+符文时,我的代码就明显变得轻巧了。
class Rune {
public $name, $stats, $image;
public function __construct($name, $stats, $image){
$this->name = $name;
$this->stats = $stats;
$this->image = $image;
$this->rune_ilvl = 1;
}
public function createTooltip() {
$tooltip = "<span class='rune-tooltip'>" . $this->name . "</span><br><span class='white-tooltip'>Item Level: 1<br>Can be inserted into socketed items<br><br>";
foreach ($this->stats as $key=>$value){
$tooltip .= "<span class='white-tooltip'>" . $key . ": " . $value . "</span>";
$tooltip .= "<br>";
}
$tooltip .= "<br><span class='white-tooltip'>Required Level " . $this->rune_ilvl . "</span>";
echo '<img class="rune-image" src="' . $this->image . '" data-toggle="tooltip" data-html="true" title="' . $tooltip . '" />';
}
}
$el_rune_oop = new Rune("El", $el_stats, "/images/runes/El_Rune.png");所以我的问题是。以前,每当我想用很酷的工具提示调用符文项目的图像时,我只需执行"echo $el_rune“即可。现在,如果我想做同样的事情,我需要回显$el_rune_oop->createTooltip()。它做的是同样的事情。但我在调用它或使用它做一些很酷的事情时遇到了问题,因为使用变量,我可以将它包含到新的数组和新的结构中,而且很容易记住……每当我在任何地方提到$el_rune_oop->createTooltip()时,它都会执行,这给我带来了各种问题。我尝试将$el_rune_oop->createTooltip()本身保存到一个变量中,这将是一个救命稻草,但这当然不起作用。
有没有什么办法可以拯救我,或者只是继续不使用面向对象的方法?
发布于 2020-05-22 23:30:01
Nigel Ren已经在上面的评论中给出了解决方案。
不是在createTooltip方法的最后一条语句中使用"echo“,而是”返回“函数生成的值。
return '<img class="rune-image" src="' . $this->image . '" data-toggle="tooltip" data-html="true" title="' . $tooltip . '" />';https://stackoverflow.com/questions/61958217
复制相似问题