在 Laravel 中,PHP 本身没有内置的结构体概念,但可以通过以下方式实现类似功能:

1. 使用类(Class)定义结构化数据

php

// 定义用户信息结构

class UserProfile

{

public string $name;

public string $email;

public int $age;

public ?string $avatar; // 可空属性

}

2. 实例化与使用

php

// 创建实例

$profile = new UserProfile();

$profile->name = 张三profile->email = angsan@example.comn$profile->age = 28;

$profile->avatar = /to/avatar.jpg 访问属性

echo $profile->name; // 输出:张三

// 作为参数传递

function sendWelcomeEmail(UserProfile $user) {

Mail::to($user->email)->send(new WelcomeMail($user));

}

3. 使用构造函数初始化

php

class ProductInfo

{

public function __construct(

public string $name,

public float $price,

public int $stock

) {}

}

// 快速实例化

$product = new ProductInfo( 5999.99, 50);

4. 集合中使用

php

$users = collect([

new UserProfile(/*...*/),

new UserProfile(/*...*/)

]);

$users->each(function (UserProfile $user) {

// 处理每个用户

});

5. 与 Eloquent 模型结合

php

// 在模型中使用

class User extends Model

{

public function profile(): UserProfile

{

return new UserProfile(

$this->name,

$this->email,

$this->age

);

}

}

// 调用

$user->profile()->email;

最佳实践建议:

1. 类型声明:使用 PHP 7.4 的类型属性(如 `public string $name`)

2. 不可变性:对重要数据使用 `readonly` 属性

3. 验证:在构造函数中添加数据验证

4. DTO 模式:适合复杂场景的数据传输对象

php

// 完整示例

class OrderDTO

{

public function __construct(

public readonly string $orderId,

public readonly float $amount,

public readonly DateTime $createdAt

) {

if ($amount <= 0) {

throw new InvalidArgumentException(必须大于0n }

}

}

这种模式在 API 开发、服务间数据传输和复杂业务逻辑中特别有用,能提高代码可读性和类型安全性。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐