Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SPL objectstorage vs SPL array vs ordinary array

Tags:

arrays

php

spl

what is the difference,*usage* scenerio between normal ARray, SPL array and SPL datastorage? It would be great if anyone can give some practical example of usage of SPLarray and SPL objectsrorage.

like image 414
varuog Avatar asked Jul 21 '12 12:07

varuog


1 Answers

The main advantage of SplFixedArray is that for a certain subset of use cases for arrays, it is much faster (that subset being arrays that have only integer keys, and a fixed length). So, for example:

$a = array("foo", $bar, 7, ... thousands of values ..., $quux);
$b = \SplFixedArray::fromArray($a);

// here, $b will be much faster to use than $a

The usage for this class could literally be anything you could use an array for, but found them to previously be too slow. A lot of times this is the case in complex calculations on large data sets. For your typical PHP-based web application or website, there aren't going to be many (if any) cases where you'd need the performance boost.


The SplObjectStorage class, however, can be useful in all kinds of typical cases. It provides a way to map objects to other data. So, for example, maybe you have a Route class that you'd like to provide a mapping to a Controller class:

$routeOne = new Route(/* ... */);
$routeTwo = new Route(/* ... */);

$controllerOne = new Controller(/* ... */);
$controllerTwo = new Controller(/* ... */);

$controllers = new \SplObjectStorage();

$controllers[$routeOne] = $controllerOne;
$controllers[$routeTwo] = $controllerTwo;

// now you can look up a controller for a given route by:  $controllers[$route]
like image 180
FtDRbwLXw6 Avatar answered Oct 14 '22 11:10

FtDRbwLXw6