class A
{
public function __construct()
{
$this->default = 'the default';
}
public function one($args = $this->default) //here
{
...
}
public function two($args = $this->default) //here
{
...
}
}
I want to change the default value only one place, and it update in every place, how can I implement that?
I dont understand question but you probably wont something like this ...
class A
{
private $default;
public function __construct($default = 'the default')
{
$this->default = $default;
}
public function one() //here
{
$this->default = "some other value"; // if you wont change value
}
public function two() //here
{
$this->default = "some other value"; // if you wont change value
}
}
You can do it like that, something like this is possible though
public function __construct()
{
$this->default = 'something';
}
public function one($param = null)
{
$this->setDefaultParam($param);
// Your code here
}
public function two($param = null)
{
$this->setDefaultParam($param);
// Your code here
}
protected function setDefaultParam($param = null)
{
if ($param) {
$this->default = $param;
}
}
You can also always give the variable to the constructor instead
public function __construct($param = null)
{
$this->default = $param ?? 'default'; // Note that this only works in PHP 7 or higher
}
class A
{
protected $default = 'Hello World';
public function one($default = null)
{
$default = $this->getDefault($default);
}
public function two($default = null)
{
$default = $this->getDefault($default);
}
protected function getDefault($default = null)
{
// We put the logic here instead
return ! is_null($default) ? $default : $this->default;
// If you're running PHP 7+, you could use this instead
return $default ?? $this->default;
}
}
@kocoten1992 Yes, but fewer lines does not automatically mean better code or better practice. These few extra lines actually apply the single responsibility principle to your code.