我有一个核心类,我无法修改核心类。我的核心类代码如下
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
获取父类。
尝试更改扩展类,如下所示:
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;
}
}
在基类中创建一个函数来计算容器计数,并在子类中使用该函数来获取容器的总数。
class Test
{
private $container = [];
public function sample($input)
{
return array_push($this->container, $input);
}
// counts container
public function countContainer(){
return count($this->container);
}
}
现在在子类中调用此 countContainer 函数。