A
A
Alexander Bagirov2015-01-01 22:56:31
PHP
Alexander Bagirov, 2015-01-01 22:56:31

What is public and why doesn't a PHP function work?

Good evening!
I am learning OOP in PHP at CodeCademy.
I got this code:

<!DOCTYPE html>
<html>
  <head>
    <title>Reconstructing the Person Class</title>
      <link type='text/css' rel='stylesheet' href='style.css'/>
  </head>
  <body>
      <p>
        <!-- Your code here -->
        <?php
            class Person {
                public $isAlive = true;
                public $firstname;
                public $lastname;
                public $age;
            }
            
            public function __construct($firstname, $lastname, $age) {
                $this->firstname = $firstname;
                $this->lastname = $lastname;
                $this->age = $age;
            }
            
            $teacher = new Person("boring", "12345", 12345);
            $student = new Person("Alex", "Bagirov", 15);
            
            echo $teacher->isAlive;
            
            public function greet() {
                return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
            }
            echo $teacher->greet();
            echo $student->greet();
        ?>
      </p>
    </body>
</html>

For some reason, the system accepted it as the right decision, but at the same time, the compiler displays the following error:
Parse error: syntax error, unexpected T_PUBLIC on line 18

What is wrong here?
Tell me more, please, what is public?
For example, they said to write public before functions, but I didn’t find a special explanation of its meaning in the Codecademy theory. Thanks for the help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Reistlin, 2015-01-01
@alexbagirov

public function __construct must be defined in the class:

class Person {
                public $isAlive = true;
                public $firstname;
                public $lastname;
                public $age;
            
            public function __construct($firstname, $lastname, $age) {
                $this->firstname = $firstname;
                $this->lastname = $lastname;
                $this->age = $age;
            } 
}

also your greet method must be defined in the class, otherwise it will not work
. I advise you to read George Schlossnagle's books "Professional Programming" or Matt Zandstra's "PHP. Objects, Patterns and Programming Techniques", perhaps you will better understand what OOP is

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question