在PHP中构造数据类型?

ktm*_*ktm 67 php

任何人都可以给我php中的结构数据类型的例子吗?为什么突然之间会出现像php这样的结构?

小智 96

最接近结构的是一个公共所有成员的对象.

class MyStruct {
    public $foo;
    public $bar;
}

$obj = new MyStruct();
$obj->foo = 'Hello';
$obj->bar = 'World';
Run Code Online (Sandbox Code Playgroud)

我会说看看PHP类文档是值得的.如果您需要一次性结构,请使用alex的答案中提到的StdObject.

  • 这将是`class MyStruct`而不是`object MyStruct`;) (4认同)

ale*_*lex 46

您可以使用数组

$something = array(
   'key' => 'value',
   'key2' => 'value2'
);
Run Code Online (Sandbox Code Playgroud)

与标准对象.

$something = new StdClass();

$something->key = 'value';
$something->key2 = 'value2';
Run Code Online (Sandbox Code Playgroud)


Rue*_*uel 5

我推荐两件事。首先是关联数组

$person = Array();
$person['name'] = "Joe";
$person['age'] = 22;
Run Code Online (Sandbox Code Playgroud)

二是上课

详细文档在这里:http : //php.net/manual/en/language.oop5.php


Max*_*Max 5

这在 Google 上的排名相当高,所以我想我应该分享我使用 PHP8 语法实现的伪结构。toArray() 方法确实依赖于 Illuminate\Support\Str 将键转换为蛇形大小写(对于针对 Laravel 模型的批量分配很有用),但是如果它不适合您的用例,只需将其删除。

基类:

<?php

namespace App\Infrastructure\Structs;

use App\Infrastructure\Exceptions\CannotMutateStructException;
use App\Infrastructure\Exceptions\ClassPropertyNotFoundException;
use Illuminate\Support\Str;
use ReflectionClass;

abstract class Struct
{
    /**
     * @param string $name
     * @param mixed $value
     * @throws CannotMutateStructException
     */
    public function __set(string $name, mixed $value): void
    {
        throw new CannotMutateStructException(
            'Structs are immutable. If you need mutable data then use a class instead.'
        );
    }

    public function all(): array
    {
        $reflector = new ReflectionClass(static::class);
        $response = [];

        foreach ($reflector->getProperties() as $property) {
            $response[$property->name] = $this->{$property->name};
        }

        return $response;
    }

    public function toArray(bool $snakeCase = false): array
    {
        $all = self::all();

        if ($snakeCase === false) {
            return $all;
        }

        $snakeCaseAll = [];

        foreach ($all as $key => $value) {
            $snakeCaseAll[Str::snake($key)] =  $value;
        }

        return $snakeCaseAll;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用:

<?php

namespace App\Infrastructure\Structs;

class Person extends Struct
{
    public function __construct(
        public string $name,
        public int $age,
        public int $heightInCentimetres,
    ) {}
}
Run Code Online (Sandbox Code Playgroud)

如何与其互动:

>>> $t = new \App\Infrastructure\Structs\Person('Max', 26, 182);

>>> $t->age
=> 26

>>> $t->age = 40
App\Infrastructure\Exceptions\CannotMutateStructException with message 'Structs are immutable. If you need mutable data then use a class instead.'

>>> $t->toArray(true)
=> [
     "name" => "Max",
     "age" => 26,
     "height_in_centimetres" => 182,
   ]
Run Code Online (Sandbox Code Playgroud)

希望这对某人有帮助。

编辑:在 PHP8.1 中,我们现在拥有只读属性,这可以使其更加简洁。

编辑:使用 PHP8.2,我们现在有一种简洁的方法来执行此操作。我强烈建议您完整阅读这篇文章以获得一个很好的例子: https: //stitcher.io/blog/evolution-of-a-php-object

然而,一般的要点是编写readonly class Foo {}不需要将其添加到每个属性的操作。