why do you give me this error Undefined variable:?

5

Excuse me I'm new to PHP and I'm only doing tests so I do not know why this error is generated:

  

Notice: Undefined variable: firstName in   C: \ xampp \ htdocs \ Programming \ PHP \ prueba.php on line 8

     

Notice: Undefined property: person :: $ in   C: \ xampp \ htdocs \ Programming \ PHP \ prueba.php on line 8

     

Notice: Undefined variable: lastName in   C: \ xampp \ htdocs \ Programming \ PHP \ prueba.php on line 8

     

Notice: Undefined property: person :: $ in   C: \ xampp \ htdocs \ Programming \ PHP \ prueba.php on line 8

<?php

class person{
    var $firstName=null;
    var $lastName=null;

    function fullname(){
            return $this->$firstName . ' ' . $this->$lastName;
    }
}

$person1 = new person;
$person1->firstName = 'Samuel';
$person1->lastName = 'Vieyra';


exit($person1->fullname());
?>

Update1

<?php

class person{
    var $firstName=null;
    var $lastName=null;

    function fullname(){
            return $this->$firstName . ' ' . $this->$lastName;
    }
}

$person1 = new person();
$person1->firstName = 'Samuel';
$person1->lastName = 'Vieyra';


exit($person1->fullname());
?>
    
asked by Samuel Viema 06.07.2018 в 06:17
source

1 answer

4

It is a syntax error, it is due to the $ that refers to the property within the line return $this->$firstName . ' ' . $this->$lastName;

The correct thing would be

return $this->firstName . ' ' . $this->lastName;

Complete code:

class person{
    var $firstName=null;
    var $lastName=null;

    function fullname(){
            return $this->firstName . ' ' . $this->lastName;
    }
}

$person1 = new person;
$person1->firstName = 'Samuel';
$person1->lastName = 'Vieyra';


exit($person1->fullname());

I recommend reading the php object orientation documentation which is very complete, and it's going to help a lot!

Greetings and successes!

    
answered by 06.07.2018 / 06:31
source