我有一个存储有关网络数据包的数据的类:
var $from_ip;
var $to_ip;
var $from_port;
var $to_port;
var $tcp_length;
var $tcp_stream_text;
var $tcp_stream;
var $tcp_sequence_dec;
现在,我正在创建打印它的功能:
function Print_data()
{
echo "<table>";
echo "<tr><td>";
echo "From IP:";
echo "</td><td>";
echo $this->from_ip;
echo "</td></tr>";
echo "<tr><td>";
echo "To IP:";
echo "</td><td>";
echo $this->to_ip;
echo "</td></tr>";
echo "</table>";
}
有没有办法优化它?你可能会注意到会有很多相同的线条。 (执行,可能是写一个函数来显示它)。但是变量怎么样?
答案 0 :(得分:1)
您的变量don't need the var
on them,但如果他们在课堂上,我建议您定义他们的访问级别(private
,public
,protected
等):
private $from_ip;
private $to_ip;
private $from_port;
private $to_port;
private $tcp_length;
private $tcp_stream_text;
private $tcp_stream;
private $tcp_sequence_dec;
这就是我(亲自)编写Print_data()
函数的方式:
function Print_data() {
?>
<table>
<tr>
<td>From IP:</td>
<td><?php echo $this->from_ip ?></td>
</tr>
<tr>
<td>To IP:</td>
<td><?php echo $this->to_ip ?></td>
</tr>
</table>
<?php
}
答案 1 :(得分:1)
尝试使用数组!使用关联数组将键设置为您想要的任何内容,我只引用了变量名称。而价值观就是你现在拥有的价值观。
$data = array(
"To IP" => $to_ip,
"From IP" => $from_port,
"To Port" => $to_port,
"TCP Length" => $tcp_length,
"TCP Stream Text" => $tcp_stream_text,
"TCP Stream" => $tcp_stream,
"TCP Sequence Dec" => $tcp_sequence_dec
);
然后迭代!使用foreach循环来获得关键和价值,以及繁荣。更清洁
function Print_data() {
echo "<table>";
foreach ($this->data as $key => $value) {
echo "<tr><td>$key</td><td>$value</td></tr>";
}
echo "</table>";
}
答案 2 :(得分:1)
正如What does PHP keyword 'var' do?所述,var已被弃用。
这是我建议的解决方案,
<?php
class TCP {
protected $from_ip;
protected $to_ip;
protected $from_port;
protected $to_port;
protected $tcp_length;
protected $tcp_stream_text;
protected $tcp_stream;
protected $tcp_sequence_dec;
private $template = "<table>
<tr>
<td>From IP:</td>
<td>%s</td>
</tr>
<tr>
<td>To IP:</td>
<td>%s</td>
</tr>
</table>";
static public function render_template() {
return sprintf(self::$template, self::$from_ip, self::$to_ip);
}
}
print TCP::render_template();
答案 3 :(得分:0)
这应该适合你的班级
var $from_ip, $to_ip, $from_port, $to_port, $tcp_length, $tcp_stream_text, $tcp_stream, $tcp_sequence_dec;
function Print_data()
{
echo <<<EOF
<table>
<tr><td>
From IP:
</td><td>
$this->from_ip
</td></tr>
<tr><td>
To IP:
</td><td>
$this->to_ip
</td></tr>
</table>
EOF;
}
答案 4 :(得分:0)
也许不是最快的,但我使用类似的东西将对象转换为assoc。阵列:
public function printObject($object)
{
$reflectionClass = new ReflectionClass(get_class($object));
foreach ($reflectionClass->getProperties() as $property)
{
$property->setAccessible(true);
echo "Prop: {$property->getName()}, Value: {$property->getValue($object)} \n";
$property->setAccessible(false);
}
}