Error in a class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
axmug
Forum Newbie
Posts: 1
Joined: Thu Mar 08, 2012 2:36 am

Error in a class

Post 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
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Error in a class

Post 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();
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Re: Error in a class

Post 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)
Post Reply