Jump to content

Question about Classes.


Lamez

Recommended Posts

I am working on my Pool class (base) and my FootballPool class (derived). I have this as my constructor

 

Pool.php

	protected $pid, $uid, $pkid, $name;
	function __construct($pid, $uid){
		$this->pid = $pid;
		$this->uid = $uid;
		$this->pkid = $this->pkid();
		if(isset($_SESSION['picksInfo']['name']))
			$this->name = $_SESSION['picksInfo']['name'];
		else
			$this->name = NULL;	
	}

 

Now a function in my FootballPool class needs to call $pid, $uid, and $pkid. How can I do that?

I have tried this: Pool::$pid, but then I get this error

 

Fatal error: Access to undeclared static property: Pool::$pid in /var/www/core/includes/FootballPool.php on line 31

 

I am confused, because in the parents constructor, it is set.

 

So basically, how can I call a variable set in the base class from a child or derived class?

Link to comment
https://forums.phpfreaks.com/topic/221237-question-about-classes/
Share on other sites

You can't access those statically. this :: is used to access static 'things'. However, you need to access these variables as an object as that is how they are set.

 

Pool::$pid

 

should be

 

$this->pid;

 

..if used within your extended class.

@OOP:

 

Okay, I was having trouble a while ago, but I had the variables set as private, then I was getting an error saying that it was not a property of FootballPool. I just tried what you suggested and it worked.

 

So if in the base class, the property that I am trying to access has to be protected and above? If private, it only belongs to the base, or that class?

@OOP:

 

Okay, I was having trouble a while ago, but I had the variables set as private, then I was getting an error saying that it was not a property of FootballPool. I just tried what you suggested and it worked.

 

So if in the base class, the property that I am trying to access has to be protected and above? If private, it only belongs to the base, or that class?

 

If it is private, only that class can access it. This rings true for methods too.

 

To access private variables of a class outside that class you have to use a 'getter' like so:

 


function getPid(){
  return $this->pid;
}

 

Then in your extended class or really anywhere now after you have instantiated the object:

 

$this->getPid();

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.