0

I have just started playing with php. My first script works fine:

<?php
echo "hello";
?>

When I require the following external php file the result is strange:

<?php
require "gloo.php";
echo "hello";
?>

gloo.php contains a single line of text:

$foo="foo1";

When I run the script the browser displays the contents of gloo.php:

$foo="foo1"hello

It is as if I typed

echo "$foo='foo1'hello"

What am I doing wrong? Thanks for your help!

0

5 Answers 5

2

gloo.php contains a single line of text:

$foo="foo1";

This file also requires the <?php and ?> tags. Which from the way you've said "contains a single line of text" I assume to not be there. The closing ?> tag is optional by the way.

Sign up to request clarification or add additional context in comments.

Comments

2

When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.

PHP also allows for short tags <? and ´?>` (which are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.

If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

<?php $foo="foo1";

is the final result.

From php.net manual.

Comments

1

Even files you include need to have a PHP code block.

<?php
   ...

Comments

1

"gloo.php":

<?php
  $foo = "foo1";
?>

Don't forget the php ;)

Comments

1

Within gloo.php, are the contents wrapped within a PHP tag? Anything outside of a PHP tag within a .php file is parsed as HTML.

Example - gloo.php;

<?php
     $foo = "foo1";
?>

That would then not display anything unless you explicitly called the variable $foo

You can also leave out the closing tag, and it is actually recommended by many developers as it rules out any issues pertaining to whitespace when developing apps or php projects. (which can be an issue)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.