-2

Can someone explain me the $this-> and the -> and the whole public function __construct

here is my code

<?php
class Person {



 public function __construct($firstname, $lastname, $age) {
     $this->firstname = $firstname;
     $this->lastname = $lastname;
     $this->age = $age;
 }
public function greet(){
    return "Hello, my name is" . $this->firstname . " " .$this->lastname .     "Nice to meet you ! :-)";
    }
}
$teacher = new Person ("boring", "12345", 12345);
$student = new Person("Mihail", "Dimitrovski", 1995);
 echo $student->age;
echo $teacher->greet();
?>

3 Answers3

1

A class is a blueprint. When you create a class like this for example:

class Person
{
    function __construct($firstName, $lastName, $age)
    {

    }

    $firstName;
    $lastName;
    $age;
}

you're essentially describing what a person is. Every instance of that class, every person will contain those 3 properties (first name, last name and age).

If you instantiate a new person like this:

$student = new Person("Mihail", "Dimitrovski", 1995);

You can use the -> operator to access those 3 properties:

echo $student->firstName;
echo $student->lastName;
echo $student->age;

You do the same thing when you want to access those properties from within the object itself. So if you have a function within your Person class that prints, say, the full name:

function fullName()
{
    echo $this->firstName . ' ' . $this->lastName;
}

you need a way to reference those properties but since you don't yet have an instance you use $this to denote that you're refering to the current instance whatever that is

dimlucas
  • 5,040
  • 7
  • 37
  • 54
0

$this-> is used to access properties or methods of a class within a class, whereas $person-> will be used when you want to access methods and variable of class outside the class.

chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
0

Everytime if you want to access a property or a method inside of an object you call it with ->.

For example, $student->age calls the age property of student.

In Java it would look like this: student.age. It is just a way of calling methods and properties of an object.

If you call $this->firstname you call the properties of the class in which you are coding at the moment.

For example:

class Person
{
    public $name;

    public function __construct($someString, $someString2, $number)
    {
        // Write your code here.
    }

    public function greet()
    {
        echo "Hey, my name is " . $this->name.
    }
}

The __construct method will be called every time you init a new instance of an object, i.e.:

$studen = new Person("boring", "12345", 12345);
sy__
  • 43
  • 7