In PHP it is possible to declare a variable at the same time that we pass it as a parameter of a function or in the instantiation of the class.
I'll give an example with the function is_file
and the class ArrayObject
.
$arrayObject = new ArrayObject($a = []);
var_dump($a); // Imprime: array(0) {}
is_file($b = 'index.php');
print_r($b); // Imprime: "index.php";
However, when we do this in stdClass
, something unexpected happens.
$object = new stdClass($c = []);
print_r($c); //Undefined variable 'c'
Note : To prove that I'm not inventing, here's the code in IDEONE
Update : Because the posted responses speak about having to do with the parameters exist in the class or function constructor, or not for assignment to occur when we assign the value to a variable that at the same time we pass as parameter, I am putting a sample code to prove that this is not true.
I created three scenarios.
- The first class
ComParametro
accepts only one parameter in the constructor - The second class
SemParametro
does not accept any parameters in the constructor, as in the case ofstdClass
- Finally, we have
stdClass
.
Let's see:
class ComParametro { public function __construct($parametro){} } class SemParametro { public function __construct(){} } new ComParametro($a = 'a'); print_r($a); new SemParametro($b = 'b'); print_r($b); new stdClass($c = 'c'); print_r($c);
As we can see in IDEONE , the results were respectively:
a b Undefined variable 'c'
So what I want to know is why this behavior is present in stdClass
!