PHP code example of andaniel05 / object-collection
1. Go to this page and download the library: Download andaniel05/object-collection library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
andaniel05 / object-collection example snippets
use Andaniel05\ObjectCollection\ObjectCollection;
class Person
{
public $name;
public $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
}
$andy = new Person('andy', 27);
$andria = new Person('andria', 35);
$sonia = new Person('sonia', 52);
$antonio = new Person('antonio', 54);
$collection = new ObjectCollection('Person');
// Inserción con índices.
$collection['andy'] = $andy;
$collection['andria'] = $andria;
// Inserción sin índices (añade al final del array).
$collection[] = $sonia;
$collection[] = $antonio;
// Recorridos en forma de array. Hay garantía de que $person será siempre una
// instancia de la clase Person.
foreach ($collection as $index => $person) {
echo "Index: {$key}, Name: {$person->getName()}, Age: {$person->getAge()}\n";
}
// Contar elementos.
echo count($collection); // Devuelve 4.
// Obtener elementos.
$andy1 = $collection['andy'];
// Comprobar existencia de elementos.
echo isset($collection['andy']); // Devuelve TRUE.
// Eliminar elementos.
unset($collection['andria']);
// Obtener el array de la colección.
$array = $collection->getArray();
use Andaniel05\ObjectCollection\ObjectCollection;
/**
* Tipo de colección personalizada que solo admite instancias de la clase 'Person'.
*/
class PersonCollection extends ObjectCollection
{
public function __construct()
{
parent::__construct('Person');
}
}
// Sobre las instancias de la clase PersonCollection se aplican las mismas
// operaciones del ejemplo anterior.
$collection = new PersonCollection;
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.