tags:

views:

83

answers:

2

Can someone tell me why I cannot write a class as follows

<?php
class Foo 
{
?>
<?php
       function bar() {
           print "bar";
       }
}
?>

I think it's the same as

<?php
class Foo 
{
       function bar() {
           print "bar";
       }
}
?>
+2  A: 

?>...<? is syntactically a statement, like "echo", or "return", therefore the first one is the same as

<?php
 class Foo 
 {
   echo "";

   function bar() {
       print "bar";
   }
}

which is not allowed

stereofrog
+8  A: 

I suppose it's because of this (quoting the Instruction separation section of the manual) :

The closing tag of a block of PHP code automatically implies a semicolon


This means that your code :

<?php
class Foo 
{
?>
<?php
       function bar() {
           print "bar";
       }
}
?>

Is the same as :

<?php
class Foo 
{;
   function bar() {
       print "bar";
   }
}
?>

Which explains the error you get :

Parse error: syntax error, unexpected ';', expecting T_FUNCTION



EDIT : Thinking a bit more about it, I thought that this was strange, considering I often use stuff like this in my templates files :

<?php if (...) : ?>
    blah
    blah
<?php endif ; ?>


So I tried this :

<?php
if (true)
{
?>
<?php
    echo "Hello, World!";
}
?>

And it works perfectly fine. OK...
Now, let's try adding the ;, like ?> is supposed to do :

<?php
if (true)
{;
    echo "Hello, World!";
}
?>

This is working fine too, and I get the following output :

Hello, World!


And, if changing the condition, just to be sure :

<?php
if (false)
{;
    echo "Hello, World!";
}
?>

Gives no output, and not error.


Considering the sentence I quoted earlier, this is not so surprising... But, still, I'm surprised anyway ^^

Pascal MARTIN
yeah,you're right,totally same error infos.
SpawnCxy