我刚开始学习PHP。我看了一个关于使用PHP在WordPress中构建主题的教程。我想问一下术语"包装器",因为我知道PHP代码的包装器是<?php ?>
。首先请看下面的代码:
<?php
$lastBlog = new WP_Query('type=post&posts_per_page=1');
if( $lastBlog->have_posts() ):
while( $lastBlog->have_posts() ): $lastBlog->the_post(); ?>
<?php get_template_part('content', get_post_format()); ?>
<?php endwhile;
endif;
wp_reset_postdata();
?>
和
<?php
$lastBlog = new WP_Query('type=post&posts_per_page=1');
if( $lastBlog->have_posts() ):
while( $lastBlog->have_posts() ): $lastBlog->the_post();
get_template_part('content', get_post_format());
endwhile;
endif;
wp_reset_postdata();
?>
在使用包装器的方式上有一点不同。我很困惑,哪个更好?两者都以同样的方式奔跑。对不起,如果这个问题看起来很荒谬。
我已经搜索了这个话题,我没有回答我的问题。说"包装器"而不是"限制器"对吗?
官方文档称它们为开始和结束标记:
当PHP解析一个文件时,它会查找开始和结束标记,其中是
<?php
和?>
,它们告诉PHP开始和停止解释他们之间的代码。以这种方式解析允许PHP嵌入各种不同的文件,如同一切之外的一副开始和结束标签被PHP解析器忽略。
"代码包装器"通常被理解为一个类或一个库,它在一个简化的编程接口下封装了许多低级操作。例如,装饰器模式也被称为包装器,因为其思想是创建一个类,它将向另一个类添加额外的功能,而不改变其他类的结构。
示例包装器(装饰器)
<?php
class Rectangle {
private $width, $height;
public function __construct($w, $h) {
$this->width = $w;
$this->height = $h;
}
public function getArea() { return $this->width * $this->height; }
public function getWidth() { return $this->width; }
public function getHeight() { return $this->height; }
}
// Decorator
class ImprovedRectangle {
protected $rect;
public function __construct(Rectangle $r) {
$this->rect = $r;
}
public function getPerimeter() {
return 2 * ($this->rect->getWidth() + $this->rect->getHeight());
}
}
$rect = new Rectangle(2, 3);
$irect = new ImprovedRectangle($rect);
echo $irect->getPerimeter(); // 10
这取决于上下文。如果我们讨论的是模板代码,其中标记代码是主要的,那么将PHP标记称为"PHP包装器"是非常正确的。但是在PHP模型(一个类或一组函数)的上下文中,PHP标记(通常只有开始标记)是强制性的,我们主要关注代码结构。
开始标记<?php
和结束标记?>
内的所有内容将由PHP处理器处理。我听说过这些叫做PHP岛屿。由于在具有更多开始和结束标记的示例中,<?php ?>
岛之外没有代码,因此代码运行相同。如果你把代码放在岛之外,它将被打印为纯文本,而不是发送到PHP进程。
在你的例子中,它没有什么区别,但为了可读性,我只会有一组<?php ?>
标签。