3
In PHP it is possible to declare a variable at the same time as we pass it as a function parameter or at class instantiation.
Let me give you 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";
But when we do it in stdClass
, something unexpected happens.
$object = new stdClass($c = []);
print_r($c); //Undefined variable 'c'
Note: To prove I’m not making it up, here comes the code on IDEONE
Updating: Because the posted answers talk about have to do with the parameters in the class or function constructor, or not so that the assignment happens when we assign the value to a variable that at the same time we pass as parameter, I am putting an example 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 meter in the constructor, as in the case ofstdClass
- And lastly, we have the
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 the IDEONE, the results were respectively:
a b Undefined variable 'c'
So what I want to know is why this behavior is present in stdClass
!
To prove I’m not making it up... :D
– Jorge B.