Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class definition problem

Tags:

php

class

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";
       }
}
?>
like image 861
Young Avatar asked Aug 31 '26 17:08

Young


1 Answers

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 ^^

like image 100
Pascal MARTIN Avatar answered Sep 03 '26 23:09

Pascal MARTIN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!