Jump to content

How arrays accessed without defining an array?


eldan88

Recommended Posts

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));

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.