开发者

PHP: Should you ever do this?

开发者 https://www.devze.com 2023-03-31 10:38 出处:网络
If I\'m creating a PHP class, should I ever have a function that looks like: <? class test { public function hello() {

If I'm creating a PHP class, should I ever have a function that looks like:

<?
class test {
public function hello() {
?>
Hello
<?
}
}
?>

I know it works, but is it consi开发者_高级运维dered to be bad programming, like, should you avoid doing things like this?


If you are trying to adhere to coding standards or readability of code, it should be something like the following. Notice how much easier it is to read and understand what is happening in the code.

<?
class test
{
   public function hello()
   {
      echo "Hello";
   }
}
?>


I prefer to avoid it when possible, but occasionally I'll do something like that because I have a block of HTML that would look terrible in echo/print statements. When I do that, I put the extra PHP tags on the same indentation for readability. Here's a rough/simple example:

<?php
// ... 
if ($foo) {
   $var = 'something';
   // ...
   ?>
   <input type="text" name="field" />
   <?php
}
?>

In a class, though, I probably wouldn't find myself mixing any HTML in there.


It works, but what is right only depends on what you are trying to accomplish. Normally I very very VERY rarely need to escape from PHP in order to print something. Except for tiny projects in which escaping a couple of times won’t hurt since it is faster for me to code that way.

What is wrong in your code in using the short tags to enter PHP. Short tags are to be deprecated and you should never rely on them anymore.


Looks fine to me, aside from not using indentation.

0

精彩评论

暂无评论...
验证码 换一张
取 消