Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $this when not in object context php

I just started learning OOPS in php. I wrote a simple program for implementing inheritance. I am getting a fatal error of $this when not in object context. Can anyone explain me this error, what does it mean? here is my code:

<?php

    class human{

        public $gender;

        public function _construct($gender)
        {
            $this->gender=$gender;

            echo $this->get_gender();
        }

        public function get_gender()
        {
            return $this->gender;
        }


    }

    class person extends human{

        public $name;
        public $surname;

        public static function set_name($name)
        {
            $this->name=$name;
        }
        public static function set_surname($surname)
        {
            $this->surname=$surname;
        }

        public static function get_name()
        {
            return $this->name;
        }
        public static function get_surname()
        {
            return $this->surname;
        }
    }

    $john = new person('male');
    $john->set_name('John');
    $john->set_surname('Williams');
    echo $john->get_name().' '.$john->get_surname().'is a '.$john->get_gender();
    ?>
like image 316
Amit Kaushal Avatar asked Jun 09 '26 15:06

Amit Kaushal


1 Answers

There are two problems here:

  1. You have defined your methods as static. You should not do that as they are not, they depend on being called on an object as you want to use the objects non-static properties.

  2. You have a typo in your constructor function. The correct name for the constructor is __construct, notice the two _ at the beginning.

like image 67
jeroen Avatar answered Jun 12 '26 08:06

jeroen



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!