Page 1 of 1

accessing class members from an extending class

Posted: Wed Nov 28, 2007 1:21 am
by s.dot

Code: Select all

<?php

class test
{
	protected $boolean = true;
	
	public function setBoolean($bool)
	{
		$this->boolean = (bool) $bool;
	}
	
	public function getBoolean()
	{
		//show this class boolean
		var_dump($this->boolean);
		
		//show class foo boolean
		$foo = new foo();
		$foo->getTestBoolean();
	}
}

class foo extends test
{
	protected function getTestBoolean()
	{
		var_dump($this->boolean);
	}
}

$test = new test();
$test->setBoolean(false);
$test->getBoolean();
This outputs:

Code: Select all

bool(false)
bool(true)
How can I access $this->_boolean from within class foo (and maintain the set value)?

Posted: Wed Nov 28, 2007 1:59 am
by Christopher
What's not working? The first false is from $test which you set to false. The second true is from $foo which still has the default value of true.

Posted: Wed Nov 28, 2007 2:01 am
by s.dot
So how do I make the class $foo recognize that $test has had it's member set to false?

Posted: Wed Nov 28, 2007 2:28 am
by Christopher
Well ... they are two different object, so:

Code: Select all

public function getBoolean()
   {
      //show this class boolean
      var_dump($this->boolean);
      
      //show class foo boolean
      $foo = new foo();
      $foo->setBoolean($this->boolean);
      $foo->getTestBoolean();
   }

Posted: Wed Nov 28, 2007 2:30 am
by s.dot
This smells of bad design to me. Do you agree?

Posted: Wed Nov 28, 2007 2:47 am
by s.dot
My real-world usage would be this:

Code: Select all

public function getStats($input, $recurse=false)
{
	if (is_file($input))
	{
		$ret = new phpsloc_file($input);
	} elseif (is_dir($input) && !$recurse)
	{
		$ret = new phpsloc_directory($input);
	} elseif (is_dir($input) && $recurse)
	{
		$ret = new phpsloc_directoryTree($input);
	} else
	{
		trigger_error('PHPsloc: Could not evaluate input file or directory', E_USER_ERROR);
	}
	
	$ret->_returnHTML = $this->_returnHTML;
	$ret->_PHPOnly = $this->_PHPOnly;
	$ret->_allowPHPTags = $this->_allowPHPTags;
	$ret->_allowSingleSpace = $this->_allowSingleSpace;
	$ret->_lineLength = $this->_lineLength;
	$ret->_lineCountPrecision = $this->_lineCountPrecision;
	
	return $ret->_getStat();
}

Posted: Thu Nov 29, 2007 5:27 am
by volka
The base knows about the extended classes? Yes, it smells ... ;)