我有一个核心类,但我不能修改核心类。我的核心类代码如下所示
class Test
{
private $container = [];
public function sample($input)
{
return array_push($this->container, $input);
}
}class Size extends Test
{
private $maxSize = 10;
public function sizeadd($element)
{
//I want get the parent container
return parent::sample($element);
}
}$sizeval = new Size();
$sizeval->sizeadd('1');
$sizeval->sizeadd('2');已成功添加值。但我的问题是,我只想添加10个值,所以我想要来自父类的count($this->container)。然后,我想检查sizeadd函数,如下所示
public function sizeadd($element)
{
if(count(container count)< $this->maxSize)
return parent::sample($element);
}我无法获取父类$container array。
发布于 2016-01-22 15:06:21
尝试更改扩展类,如下所示:
class Size extends Test
{
private $maxSize = 10;
/**
* To track how many elements are being added
*
* @var integer
*/
private static $count = 0;
/**
* Adding element in size
*
* @param integer $element
* @return integer
*/
public function sizeadd($element)
{
if (self::$count < $this->maxSize) {
self::$count = self::$count + 1;
return parent::sample($element);
}
}
/**
* This is just for getting the current number of count
* this is optional method.
* @return integer
*/
public function getCount()
{
return self::$count;
}
}发布于 2016-01-22 15:00:33
在基类中创建一个函数来计算容器数量,并在子类中使用该函数来获取容器的总数量。
class Test
{
private $container = [];
public function sample($input)
{
return array_push($this->container, $input);
}
// counts container
public function countContainer(){
return count($this->container);
}
}https://stackoverflow.com/questions/34940717
复制相似问题