Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put PHP class definition in include file

Tags:

php

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 trouble 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.

like image 502
Rob3C Avatar asked May 23 '26 12:05

Rob3C


2 Answers

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)

like image 120
Vincent Savard Avatar answered May 25 '26 23:05

Vincent Savard


It seems typo error on your classdef.php, try below:

<?php
class SimpleClass
{
    public $var = 'a def value';

    public function displayVar() {
      echo $this->var;
    }
}
like image 38
subosito Avatar answered May 25 '26 21:05

subosito



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!