Calling a Method Immediately After Object Creation in OOP in PHP
Let's say we have a class Arr
that
stores an array of numbers and can calculate
the sum of these numbers using the method getSum
.
The numbers themselves are passed as an array to the object's
constructor, and can also be added one by one
using the method add
:
<?php
class Arr
{
private $numbers = [];
public function __construct($numbers)
{
$this->numbers = $numbers;
}
public function add($number)
{
$this->numbers[] = $number;
}
public function getSum()
{
return array_sum($this->numbers);
}
}
?>
Here is an example of using the class Arr
:
<?php
$arr = new Arr([1, 2, 3]);
$arr->add(4);
$arr->add(5);
echo $arr->getSum(); // will output 15
?>
It might be the case that we pass all the necessary numbers at the moment of object creation, and then immediately want to find their sum:
<?php
$arr = new Arr([1, 2, 3]);
echo $arr->getSum(); // will output 6
?>
If we don't plan to do any further
manipulations with the object, then the code above can be
rewritten more concisely: we can create an object and
immediately call its method getSum
:
<?php
echo (new Arr([1, 2, 3]))->getSum(); // will output 6
?>
<?php
class StringProcessor
{
private $str = '';
public function __construct($text)
{
$this->str = $text;
}
public function append($text)
{
$this->str .= $text;
return $this;
}
public function getValue()
{
return $this->str;
}
public function getLength()
{
return strlen($this->str);
}
}
?>
Suppose this class was used in the following way:
<?php
$str = new Str('aaa');
$str->append('bbb');
$str->append('ccc');
echo $str->getLength();
?>
Rewrite this code by calling the class on the spot.