class API
{
public function getProduct(int $productId): Product
{
$product = $this->request(...); // Получение данных из API
return Product::from($product)
{
}
class Product
{
private int $id;
private string $title;
// прочие свойства
public function getId(): int
{
return $this->id;
}
public function getTitle(): int
{
return $this->title;
}
// прочие геттеры
// сеттеры, если нужны
public static function from(object $source): self
{
$product = new static();
$product->id = $source->id;
$product->title = $source->title;
// заполнение свойств
return $product;
}
}
...
$api = new API($login, $password);
$product = $api->getProduct(325);
$foo = ['order' => '100668327'];
echo $foo['order'];
или$foo = (object)['order' => '100668327'];
echo $foo->order;
$foo = json_decode('{"order":"100668327"}');
echo $foo->order;
или$foo = json_decode('{"order":"100668327"}', true);
echo $foo['order'];
$data = [
['id' => 1, 'field1' => 'Вася'],
['id' => 2, 'field1' => 'Петя'],
['id' => 3, 'field1' => 'Миша']
];
foreach ($data as $row) {
$stmt->execute($row);
}
или$data = [
1 => 'Вася',
2 => 'Петя',
3 => 'Миша'
];
foreach ($data as $id => $field1) {
$stmt->execute(['id' => $id, 'field1' => $field1]);
}
class A
{
private static array $instances = [];
public readonly int $value;
public function __construct(?int $value = null)
{
if ($value !== null) {
$this->value = $value;
static::$instances[] = $this;
}
}
public function summ(): int
{
return array_reduce(
static::$instances,
fn($acc, $cur) => $acc + $cur->value,
0
);
}
}
new A(2);
new A(3);
$summ = (new A())->summ();
print $summ; // 5
$json = file_get_contents('php://input');
$data = json_decode($json);
- SPL:
. Calling get_object_vars() on an ArrayObject instance will now always return
the properties of the ArrayObject itself (or a subclass). Previously it
returned the values of the wrapped array/object unless the STD_PROP_LIST
flag was specified.