'Standard' simple piece of php from W3Schools gives erroneous output

Hi - complete newbie here, I’m looking at some simple code examples which give vastly different
results on the php setup I have access to. I suspect this will prove to be mind-bogglingly simple
and will probably be quite embarrassing, but …

So, the code snippet I’m trying is:

[php]

<?php $x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo “

Variable x inside function is: $x

”;
}
myTest();

echo “

Variable x outside function is: $x

”;
?> [/php]

This gives, according to the example, the output:

[tt]Variable x inside function is:
Variable x outside function is: 5[/tt]

Ok, so far so good. Now, when I point a browser at the test.html file (containing exactly the above)
the output is:

[tt]Variable x inside function is: $x
"; } myTest(); echo "
Variable x outside function is: $x

"; ?>[/tt]

So I’m doing something fundamentally wrong. The problem is, it’s so fundamental that all of the
examples I’ve seen assume that things like the above snippet work (as I’m sure they do if only
I understood X - but I just don’t get what X is).

I realise this question is probably laughable, but there’s something I’m just not understanding.
Thankyou for your patience.

/Nick

ps: I’m running php 5.4 on a hosted service.

Normally web servers are only configured to serve PHP through .php files, try renaming your file (it will work with the way you have HTML atm even if it’s .php)

Jim - many thanks - that nailed it. I guess I don’t/didn’t understand that you can’t
serve up php generated html by embedding <?php ..... ?> in a parent html document.
That was the one key piece I was missing. I can certainly restructure my first tentative
php tests to be delivered by the browser pointing at a php file.

BTW, I’m not sure of the etiquette here - now that this is resolved do-I/can-I mark this
as resolved, or does a mod do it, or…? Thanks again…/Nick

Sponsor our Newsletter | Privacy Policy | Terms of Service