eldan88 Posted June 11, 2014 Share Posted June 11, 2014 Hey Guys. I came across this code example below assigns array values to a private property. However the private property is not defined as an array. It was a bit confusing to me because I always thought you need to define the property as an array first. If someone can please help me understand this concept I would really appreciate it. Below is the code. <?php class Product { public $name; public $price; function __construct($name, $price){ $this->name = $name; $this->price = $price; } } class ProcessSale { private $callbacks; // This holds an array but is not defined as an array? function registerCallback($callback) { if(!is_callable($callback)) { throw new Exception("Callback Is Not Callable"); } $this->callbacks[] = $callback; } function sale($product) { print "{$product->name}: processing \n"; foreach ($this->callbacks as $callback) { call_user_func($callback, $product); } } } $logger = function($product) { print "logging ({$product->name})\n"; }; $processor = new ProcessSale(); $processor->registerCallback($logger); $processor->sale(new Product("shoes", 6)); echo "\n"; $processor->sale(new Product("coffee", 6)); Quote Link to comment Share on other sites More sharing options...
Solution Jacques1 Posted June 11, 2014 Solution Share Posted June 11, 2014 PHP automatically turns a variable into an array when you treat it as an array. You can easily try it out: <?php for ($i = 0; $i < 10; $i++) $some_var[] = 'foo'; var_dump($some_var); I wouldn't recommend this, though. As you can see, it's very confusing, and the type of the variable remains unknown until the array syntax is used. It's much clearer to explicitly initialize the variable with an empty array. Quote Link to comment Share on other sites More sharing options...
maxxd Posted June 11, 2014 Share Posted June 11, 2014 It's the joy of PHP's not being a strongly-typed language. Any property or variable can hold any kind of data at any time. I agree with Jacques1 that it's better to be explicit and define the type before assigning values. Quote Link to comment Share on other sites More sharing options...
eldan88 Posted June 11, 2014 Author Share Posted June 11, 2014 I see. Thanks alot guys! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.