Jump to content

Question about PHP syntax


Kimomaru

Recommended Posts

Hello,

    It took me about an hour to work through a syntax problem in a PHP file containing functions for test web page I'm learning with.  I know how to get something to work, but I don't understand it.    In the following syntax I have included functions for a header, some main body information, and a footer.  However, I can't figure out how the the opening and closing tags relate to each other.  Please refer to commented lines before, thank you for any help or advice.

 

<?php      // This is the opening tag

function display_html_header() {

?>          // This is the closing tag

<html>  // Here is my HTML

<head>

<title>Blah Blah Blah</title>

</head>

<body>

<table width="100%" bgcolor="white" cellpadding="12" border="0">

  <tr>

    <td>

      <p><font size="10">Blah Blah Blah</font></p>

    </td>

    <td align="right">

        <? date_default_timezone_set('MST') ?>

        <? echo date('l, F jS Y'); ?>

</td>

  </tr>

  </table>

</body>

</html>

<?php    // Why is this opening tag needed here?  I understand that it's needed to make the above syntax work.  So, it's a closer?

}

 

function display_site_info() {  // Does this new section need an opener?  What that in the preceding tag?

?>

  <ul>

  <li>Blah Blah Blah!</li>

  </ul>

<?php

}

 

function display_html_footer() {

?>

<table bgcolor="white" cellpadding="12" border="0" align="center">

  <tr>

    <td>Privacy and Terms

    </td>

    <td>Contact Us

    </td>

    <td>About

    </td>

  </tr>

  </table>

</body>

</html>

<?php

}

Link to comment
Share on other sites

<?php and ?> are the opening and closing tags (respectively) for PHP itself.  However, you need to take into account braces ({ and }) within your PHP code, as they denote code blocks.  Example:

 

<?php
    if($x == true) { // note the brace
        // code
        // code
        // code
    } // <-- the closing brace ends the code that is executed if the if-conditional is true

 

When you mix PHP and HTML, you need to be aware of both the PHP tags themselves and whatever brace pairs you may have.

 

<?php
   // code
   // code

   if(/* something */) { // opening brace
?> <-- end of PHP mode, but the rest of the code is STILL taking place within the code block started by the brace above

<html>
<!-- blah
     blah
     blah -->

<?php
    } // closing brace, which closes the block - ALWAYS match braces
?>

 

Blocks are formed by loops, conditionals, and function definitions.

 

All that said, I strongly urge you to think along different lines when you write your PHP.  It's usually not a good idea to jump between PHP and HTML a lot in your code.  Why?  Maintainability, for one.  Do you really want to spend time hunting for closing braces within PHP tags, which themselves are nested in HTML?  There's also request handling to consider.

 

Well-formed PHP apps look like this:

 

PHP code to process requests, handle data, talk to the DB, etc.

|

|

|

V

All values that need to be displayed are stored in variables

|

|

|

V

Jump out of PHP into HTML when ALL data processing is completed

|

|

|

V

Pure HTML, with the exception of PHP code necessary to display values.  That code should NOT be more complicated than:

 

<?php echo $value; ?>

 

Or

 

<?php while(/* some condition */) {

              echo $value;

          }

?>

 

Or

 

<?php if(/* some condition */) {

              echo $value;

          } else {

              echo $otherValue;

          }

?>

 

That may sound overly restrictive, but it's really the best way to go.  It ensures that both your PHP and HTML are clean and easy to read, and will allow you to avoid the popular "Headers already sent" error.

Link to comment
Share on other sites

Hey Kevin,

    Now I'm even more confused, but I suspect that it's due mainly to my lack of experience.  I'm working off of the book entitled "PHP and MySQL Web Development (4th Edition)", this is how they've laid out the code.  Someone in the Amazon Customer Reviews section (named Travis Parks) mentioned that this book does not teach how to write PHP properly.  It's puzzling for the newcomer and I can't tell if I'm painting myself into a corner.

 

The first example you mentioned is understandable;

 

<?php    // opening tag

    if($x == true) { // note the brace  opening brace

        // code

        // code

        // code

    } // <-- the closing brace ends the code that is executed if the if-conditional is true closing brace

 

// no closing php tag in this example, but I'm assuming it would be "<?php"  ?

 

The second example is harder to understand;

 

<?php    open

  // code

  // code

 

  if(/* something */) { // opening brace brace is opened before the closing php tag but closed after?

?> <-- end of PHP mode, but the rest of the code is STILL taking place within the code block started by the brace above [close]

 

<html>

<!-- blah

    blah

    blah -->

 

<?php

    } // closing brace, which closes the block - ALWAYS match braces brace closed after close of block?

?>

Link to comment
Share on other sites

// no closing php tag in this example, but I'm assuming it would be "<?php"  ?

Closing php tag is ?>  Opening is <?php

 

As KevinM1 pointed out it's not a good idea to wrap html in a php bracket.

 

You give the example of a function to show header.  Personally I would make a new page called header.php and have in it.

<html>
<head>
<title>Blah Blah Blah</title>
</head>
<body>

Do the same for the footer.  Then site pages would be something like this.

<?php
//include db connection
include("access.php");

//Any processing code for user input goes above header and before any information is passed to browser//

//Include header//
include("header.php");
//Any content like forms or tables should be hard coded.//
?>
<h2>Sample Content</h2>
<?php
//Any text content saved in DB can be echoed on the page.//
echo "$pagecontent";
//Include footer//
include("footer.php");
?>

Link to comment
Share on other sites

Hi Jesirose,

    First, please recommend a good book.

    Second - with respect to the open and close PHP syntax, thank you for putting it that way, seriously.  In a post I put up yesterday someone replied to me;

 

http://forums.phpfreaks.com/index.php?topic=361252.0

 

"To close the function you have to go back into PHP code with another <?php.

<?php

function display_site_info() {

?>

  <ul>

  <li>This is test gibberish</li>

  </ul>

<?php

}"

 

So, clearly I misunderstood.  I could just close it plainly with "?>".  The context of the thread would have been referring to a situation where I would be adding another php block of code, in which case (please correct me if I'm wrong), the new opening tag would close the preceding one?

 

Link to comment
Share on other sites

If your first example

<?php     // opening tag
    if($x == true) { // note the brace  opening brace
        // code
        // code
        // code
    } // <-- the closing brace ends the code that is executed if the if-conditional is true closing brace

is the entirety of the file, then it's fine; the ending tag is not required. In fact, the Zend Framework coding standard forbids it in some cases. I prefer to make sure there's a closing tag for every opener, but there are arguments to made against that (in the case of the end of a file). In any case, if you're learning PHP get used to such inconsistencies. It's part of its "charm".

 

In the second example,

<?php      open
   // code
   // code

   if(/* something */) { // opening brace brace is opened before the closing php tag but closed after?
?> <-- end of PHP mode, but the rest of the code is STILL taking place within the code block started by the brace above [close]

<html>
<!-- blah
     blah
     blah -->

<?php
    } // closing brace, which closes the block - ALWAYS match braces brace closed after close of block?
?>

 

the PHP code is being used to ensure what's contained within the braces is sent to the browser only in the event of the conditional being met.

Link to comment
Share on other sites

Hi Drummin,

    Before this morning, I had my header and footers in separate files and called them separately.  The PHP book I'm reading suggested to put this content in a different files that contains functions for producing output.  Personally, I'm very much into a modular approach as it is easier to track and manage objects, but since I'm new it's difficult to gauge the prevailing "wisdom".

Link to comment
Share on other sites

So, clearly I misunderstood.  I could just close it plainly with "?>".  The context of the thread would have been referring to a situation where I would be adding another php block of code, in which case (please correct me if I'm wrong), the new opening tag would close the preceding one?

 

You're confusing closing a function with closing a block of PHP.

 

You really need to keep the HTML and PHP separate, and not end and start PHP within a function, or even a file. Read KevinM's post with the part about "Well-formed PHP apps look like this:"

Link to comment
Share on other sites

Hey Jesirose,

    That's what it sounds like, but I think I'm starting to understand.  Okay, question -  Why does this work;

 

<?php

function display_html_header() {

?>

<html>

<head>

<title>Blah blah blah</title>

</head>

<body>

<table width="100%" bgcolor="white" cellpadding="12" border="0">

  <tr>

    <td>

      <p><font size="10">Blah blah blah</font></p>

    </td>

    <td align="right">

        <? date_default_timezone_set('MST') ?>

        <? echo date('l, F jS Y'); ?>

</td>

  </tr>

  </table>

</body>

</html>

<?php

}

 

But this does not work;

 

<?php

function display_html_header() {

?>

<html>

<head>

<title>Blah blah blah</title>

</head>

<body>

<table width="100%" bgcolor="white" cellpadding="12" border="0">

  <tr>

    <td>

      <p><font size="10">Blah blah blah</font></p>

    </td>

    <td align="right">

        <? date_default_timezone_set('MST') ?>

        <? echo date('l, F jS Y'); ?>

</td>

  </tr>

  </table>

</body>

</html>

?>

}

 

And I already see most of the problem, there's a closing php tag that is without an opener.  The first two refer to the open and close for the function, does this mean that I need to add an opener for the code block?

Link to comment
Share on other sites

Apologies for leaving the ?> off at the end of my first example.  That was definitely not intentional.

 

I think you're over thinking it.

 

<?php <--- enters PHP mode

?> <--- leaves PHP mode

 

{ <--- starts a PHP code block

} <--- ends a PHP code block

 

That's it.

 

As far as books go, I'm not sure what would be good for an absolute beginner.  I started with an earlier edition of Larry Ullman's PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide.  It's written in a very easy to understand style, but my edition didn't really dive into best practices.

 

If that doesn't work for you, you can always try the online manual: http://php.net/manual/en/index.php  Start at the language reference and work your way down.

Link to comment
Share on other sites

Hey KevinM1,

    I went back and read your example again, and I think I understand where I was messing up.  I needed to understand at what point the PHP opens and closes were happening around the HTML, especially as they pertained to the declaration of the function and code blocks themseves.  This was stumping me;

 

<?php

function display_html_header() {

?>

<html>

<head>

<title>Blah blah blah</title>

</head>

<body>

<table width="100%" bgcolor="white" cellpadding="12" border="0">

  <tr>

    <td>

      <p><font size="10">Blah blah blah</font></p>

    </td>

    <td align="right">

        <? date_default_timezone_set('MST') ?>

        <? echo date('l, F jS Y'); ?>

</td>

  </tr>

  </table>

</body>

</html>

<?php

}

?>

 

Which is basically that php is being opened and closed for the function, then there's HTML, then it's opened and closed again for the close brace (which was opened during the function).  I think I'm going to make a conscious effort to break things down int he code more than I have.

Link to comment
Share on other sites

Anything within a set of <?php  ?> tags is parsed by the php interpreter on the web server. If the php code within the tags generates output, it is sent to the browser. Anything NOT within <?php  ?> tags is sent directly to the browser.

 

<?php
echo "Hello, world from php.<br>\n";
$variable = "this will not be output since it is simply assigned to a variable and not sent to the browser via echo.";
?>

Hello world, from html<br>
All of this will be output directly to the browser without being parsed for php code.
And this.
This as well.
$var = "this looks like a variable assignment, but it isn't, because it happens outside the <?php ?> tags. ";

<?php
$variable2 = "Another string, but this time it will be output with echo.<br>\n";
echo $variable2;
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.