Modify PHP. Customize how PHP calls a function
是否可以修改php以创建自定义方式来调用php函数,而无需打开和关闭php标签?例如,给定这样一个示例函数,该函数包含在我的静态页面中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php function title(){ $files = array( "service.php"=>"This is a Service Page Title", "index.php"=>"This is a Home Page Title", "contact.php"=>"This is a Contact Page Title" ); foreach($files as $file => $title) { $thisFile = basename($_SERVER['PHP_SELF']); if($file == $thisFile){ echo $title; break; } } }; ?> |
无论如何,有没有修改php的核心,因此可以像这样调用它:
1 | {{Title}} |
代替此:
1 | <?php title(); ?> |
似乎每个人在阳光下都在编写模板引擎,这些模板引擎使用友好的语法和双花括号来包围变量。我只是想一种避免安装其他东西的方法,而只是使用本机php。
大多数时候,完全不需要花哨的模板引擎。您可以在回显所有标记之前,通过在其他方式准备就绪的HTML(已存储到变量中)上运行标记及其值的简单str_replace循环,轻松完成此操作。这是我的工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | $html = 'My-ready-HTML with {{foo}} and {{bar}} thingys.'; // Or: $html = file_get_contents('my_template.html'); $footsy = 'whatever'; $barsie = 'some more'; $tags = [ 'foo' => $footsy, 'bar' => $barsie ]; function do_tags($tags, $html) { foreach ($tags as $key=>$val) { $html = str_replace('{{'.$key.'}}', $val, $html); } return $html; } $output = do_tags($tags, $html); echo $output; |
使用short_tags可以达到类似的效果。而不是做
1 | <?php echo $blah ?> |
做
1 | <?= $blah ?> |
或
1 | <?= callFunction() ?> |
如果您的php版本为5.4或更高,则将支持这些标记。在此之前,defaut会禁用short_tags。即使在5.4中,服务器也可以禁用它们,因此请明智地使用它。
另一种方法是在字符串中回显html,这样您就不必切换进出php。只要记住要让自己和其他人都可以阅读它:
1 2 3 4 5 6 7 8 9 10 11 | <?php $text ="Hello, World!"; echo"<html> <head> </head> <body> <span>" . $text ."</span> </body> </html>"; |
您也可以使用heredocs:
1 2 3 4 5 6 7 8 9 10 11 | $html = <<<HTML <html> <head> </head> <body> <span>$text</span> </body> </html> HTML; echo $html; |
编辑:我还想指出ob_start和ob_get_clean。这样做是"记录"应该在屏幕上打印出的所有内容,而无需将其打印出来。这样,您可以在屏幕上显示内容之前完成代码中的所有逻辑。您仍然需要打开和关闭php标签或回显包含html的字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php ob_start(); $text ="Hello, World!"; ?> <html> <head> </head> <body> <span><?= $text ?></span> </body> </html> <?php $html = ob_get_clean(); echo $html; //All output stored between ob_start and ob_get_clean is then echoed onto the web page at this point. |
这对于不需要处理大量信息的小型网页可能没有帮助。但是,如果您有很多信息要显示。通过发送大量较小的位来将大量数据发送到HTML是有益的,并且可以提高性能。
而不是:
1 | <?php echo title(); ?> |
尝试使用:
1 | <?= title() ?> |
除此之外,您最好还是使用模板引擎,因为您必须解析代码块并解释{{}}括号。
您可以将所有html代码存储在PHP变量中并在最后将其打印出,此方法可以避免许多打开和关闭PHP标记的情况。像这样:
1 2 3 4 | <?php print"<html><head>".title()."</head><body></body></html>"; ?> |
而不是:
1 | <html><head><?php echo title(); ?></head><body></body></html> |