Page 1 of 1

Error in a class

Posted: Thu Mar 08, 2012 3:02 am
by axmug
Hi,

I have an error in a class I typed, and I don't know why. My code is the following:

Code: Select all


class Persona
{
	private $nombre;
	private $apellidos;
	
	function __construct()
	 {
		$nombre="David";
		$apellidos="Garcia Roma";	
	 }
	
	function getNombre()
	 { 
		return $nombre."<br>";
	 }

	function getApellidos()
	 { 
		return $apellidos."<br>";
	 }
	 
};

$persona = new Persona();
print $persona->getNombre();

When I load the script in my webserver I display the following error:

Undefined variable: nombre in C:\wamp\www\DatosPersonas.php on line 33

Re: Error in a class

Posted: Thu Mar 08, 2012 6:48 am
by Celauran
You omitted $this

Code: Select all

class Persona
{
    private $nombre;
    private $apellidos;

    function __construct()
    {
        $this->nombre="David";
        $this->apellidos="Garcia Roma";      
    }

    function getNombre()
    {
        return $this->nombre."<br>";
    }

    function getApellidos()
    {
        return $this->apellidos."<br>";
    }
};

$persona = new Persona();
print $persona->getNombre();

Re: Error in a class

Posted: Sat Mar 10, 2012 12:47 pm
by Luke
To add to what has already been said, when in the context of an object instance, you need to use $this-> to access instance variables (ie: $this->nombre). Just as you would use $persona->nombre to access that variable from the outer scope (if it were a public property, that is)