<?php
// set a value for this example, but imagine the user
// was posting this in a form.
$_POST['var1'] = 'another_type';
$valueObj = new class($_POST['var1']) {
private $m_value;
public function __construct(string $input)
{
switch ($input)
{
case 'type1' : $this->m_value = 1; break;
case 'type2' : $this->m_value = 2; break;
case 'another_type' : $this->m_value = 3; break;
default : throw new Exception("Invalid input: $input");
}
}
public function getValue() : int { return $this->m_value; }
};
print $valueObj->getValue(); // 3
https://blog.programster.org/php7-0-anonymous-classes
I can't understand how $_POST['var1'] is assigned to $m_value inside the constructor.
CodePudding user response:
When object is created __construct function executes first. You have passed $_POST['var1'] while initialising object i.e new class($_POST['var1']) and in your constructor based on condition $this->m_value value is assigned, in your case it would be 3 as value is "another_type";
CodePudding user response:
$_POST['var']
isn't assigned to $m_value
.
When the class is created, it is instantiated with the $_POST['var']
parameter, which is in turn passed to the __construct
class constructor as $input
.
The value of $input
is then passed to the switch statement, which then assigns the value of 3
to $m_value
.
Finally, $m_value
is returned by the getValue()
function.