Jargoson
Jargoson

Reputation: 21

PHP: Should you ever do this?

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 considered to be bad programming, like, should you avoid doing things like this?

Upvotes: 2

Views: 89

Answers (4)

user912695
user912695

Reputation:

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.

Upvotes: 0

Wiseguy
Wiseguy

Reputation: 20883

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.

Upvotes: 1

Trevor
Trevor

Reputation: 6689

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";
   }
}
?>

Upvotes: 3

Kevin Parker
Kevin Parker

Reputation: 17206

Looks fine to me, aside from not using indentation.

Upvotes: -1

Related Questions