Skip to content

Instantly share code, notes, and snippets.

@alexlatam
Last active January 29, 2024 18:17
Show Gist options
  • Save alexlatam/1a5c365407f5c725a6393de40669fb55 to your computer and use it in GitHub Desktop.
Save alexlatam/1a5c365407f5c725a6393de40669fb55 to your computer and use it in GitHub Desktop.
Get an array typed with an specific class on PHP. NameClass[]
<?php
/**
* Creamos una clase de la cual se crearan los objetos que contendra el array
* El array tendra solo objetos de esta clase. [Product, Product, ...]
*/
readonly class Product
{
public function __construct(
private string $name,
private float $price
) {
}
public function getName(): string
{
return $this->name;
}
public function getPrice(): float
{
return $this->price;
}
}
/**
* Esta funcion o metodo recibira una array que contendra SOLO objetos de tipo: Product
* [Product, Product, Product, ....] [spread operator to received]
* Esto se llama 'variadic arguments'
*/
function test(Product ...$args)
{
$total = 0;
foreach ($args as $product) {
$total += $product->getPrice() * $product->getQuantity();
}
return $total;
}
$product1 = new Product(name: 'product1', price: 10);
$product2 = new Product(name: 'product2', price: 20);
$product3 = new Product(name: 'product3', price: 30);
// Agregando valor por valor
echo test($product1, $product2, $product3); // output: 60
// Agregando un array de objetos [spread operator to send]
echo test(...[$product1, $product2, $product3]); // output: 60
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment