How to put PHP class definition in include file
I'm new to PHP, having trouble when I move a class definition out of my "main" page and into an include file.
Suppose I have main.php, with the below contents. It works fine:
<?php
class SimpleClass
{
public $var = 'a def value';
public function displayVar() {
echo $this->var;
}
}
?>
<html>
<h1>blah blah blah</h1>
</html>
But now suppose that I try removing the class definition and putting it in a separate file, so that the main.htm now looks like:
<?php
include("classdef.php");
?>
<html>
<h1>blah blah blah</h1>
</html>
and classdef.php is:
<?php
class SimpleClass
{
public $var = 'a def value';
public function displayVar() {
echo $this->var;
}
?>
Then when I view my main.php, it displays as
var; } } ?>
blah blah blah
As if the >
character in the $this->var
is interpreted as closing the PHP. I've had t开发者_开发百科rouble searching for this, in that I don't know what the ->
operator is called.
This is PHP 5.3.3 on Apache 2.2 on Windows.
Your PHP isn't being interpreted (if it was a parse error problem, well, you would get a parse error). First thing I noticed is you said you put the PHP in main.htm. Unless you explicitely set your server to interpret .htm / .html files with PHP, your server won't know you have PHP in this file.
Edit: as I said in comments, the problem is that PHP isn't being interpreted by Apache. Here are the usual problems :
- You're not calling the script correctly, for example you are calling C:\wamp\www\yourfile.php instead of http://localhost/yourfile.php
- As Wrikken said, you are using short tags (< ? instead of < ?php)
- You gave a wrong extension to your file name
I don't think it's a quote problem, otherwise you would most likely get a parse error. I'll go with what other people said and ask you to give the HTML code generated by your PHP script (access the script through your browser and press Ctrl + U)
It seems typo error on your classdef.php, try below:
<?php
class SimpleClass
{
public $var = 'a def value';
public function displayVar() {
echo $this->var;
}
}
You most probably don't start your classfile with <?php
, but nasty <?
, and short_open_tags
are disabled. Fix that (make it <?php
, leave short_open_tags
off), and it'll work. Anything between the starting <?
and the first >
after that is now sent to the user and interpreted as an HTML tag (if you look in the source, you probably see your whole class definition).
Shouldn't this be
<?php
class SimpleClass
{
public $var = 'a def value';
public function displayVar() {
echo $this->var;
}
}
?>
You are missing a }
for function displayVar()
With the latest updates from RobC, my guess is a missing or unescaped quote character. Unless we're shown the actual source, this is my best guess.
I suggest you use an IDE or editor with syntax highlighting and the problem will become obvious.
精彩评论