Jump to content

How arrays accessed without defining an array?


eldan88
Go to solution Solved by Jacques1,

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

Link to comment
Share on other sites

  • Solution

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.