How to set PHP class definition to include file

I am new to PHP, I am having problems transferring the class definition from my "main" page and into the include file.

Suppose I have main.php, with the content below. It works great:

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

    public function displayVar() {
        echo $this->var;
    }
}
?>
<html>
<h1>blah blah blah</h1>
</html>

But now suppose I try to remove the class definition and put it in a separate file, so main.htm now looks like this:

<?php
include("classdef.php");
?>
<html>
<h1>blah blah blah</h1>
</html>

and classdef.php:

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

    public function displayVar() {
    echo $this->var;
}
?>

Then, when I view my main.php file, it displays as

var; } } ?>
blah blah blah

As if the character >in is $this->varinterpreted as closing PHP. I am having trouble finding this because I don't know how the statement is called ->.

This is PHP 5.3.3 on Apache 2.2 on Windows.

+3
5

, <?php, <? short_open_tags . ( <?php, short_open_tags off), . , <? > , HTML- ( , , , ).

+2

PHP ( , , ). , , , PHP . htm. .htm/.html PHP, , PHP .

: , , PHP Apache. :

, , , , . , , HTML, PHP script ( script Ctrl + U)

+6

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

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

    public function displayVar() {
      echo $this->var;
    }
}
+3
source

Must not be

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

    public function displayVar() {
    echo $this->var;
}
}
?>

You are missing }for functiondisplayVar()

+2
source

With the latest updates from RobC, my hunch is missing or unshielded quotes. If we are not shown the actual source, this is my best guess.

I suggest you use an IDE or syntax-highlighted editor, and the problem will become apparent.

0
source

Source: https://habr.com/ru/post/1773169/


All Articles