You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Instagram类返回账户对象而非数组?修改后的实现是否正确?

实现Instagram账户对象化调用方法的解决方案

问题背景

作为类的初学者,我查找了大量资料仍未解决问题。现有Instagram类代码如下:

class Instagram
{
    public array $account = [];

    public function get_instagram_business_accounts(): array
    {
        return db()->query("SELECT followers_count FROM instagram_business_accounts ORDER BY username")->fetchAll();
    }

    public function get_followers_count()
    {
        return Miscellaneous::number_format($this->account["followers_count"]);
    }
}

目前我这样使用该类:

$accounts = new Instagram();
foreach($accounts->get_instagram_business_accounts() AS $account){
     $accounts->account = $account;
     echo $accounts->get_followers_count();
}

但我希望能这样使用:

$accounts = new Instagram();
foreach($accounts->get_instagram_business_accounts() AS $account){
     echo $account->get_followers_count();
}

即让$account作为对象调用get_followers_count()方法,请问该如何实现?


我的尝试(编辑补充)

我更新了主类并新增了InstagramAccount类,代码如下:

class Instagram
{
    public function get_instagram_business_accounts(): array
    {
        $accounts = db()->query("SELECT followers_count FROM instagram_business_accounts ORDER BY username")->fetchAll();
        $return = [];
        foreach($accounts AS $account){
            $return[] = new InstagramAccount($account);
        }
        return $return;
    }
}
class InstagramAccount
{
    private int $followers_count;

    public function __construct(array $Instagram)
    {
        foreach($Instagram AS $key=>$value){
            $this->{$key} = $value;
        }
    }

    public function get_followers_count(): string
    {
        return Miscellaneous::number_format($this->followers_count);
    }

}

请问这样的实现是否满足我的需求?


回答

你的实现完全满足需求!

原因很明确:

  • 现在get_instagram_business_accounts()方法不再返回原生数组,而是将数据库查询到的每个数组转换成InstagramAccount对象
  • 每个InstagramAccount对象都封装了followers_count属性和对应的get_followers_count()方法,完全符合你期望的$account->get_followers_count()调用方式

小优化建议

  1. 参数命名更语义化:把构造函数的参数$Instagram改成$accountData,避免和类名混淆
  2. 避免动态赋值风险:当前构造函数通过循环给属性赋值,若数据库返回类中未定义的字段会触发错误,改成显式赋值更安全:
public function __construct(array $accountData)
{
    $this->followers_count = (int)$accountData['followers_count'];
}
  1. 类型确保:加上(int)强制转换,避免数据库返回字符串类型的数字引发类型错误

内容的提问来源于stack exchange,提问作者oralunal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 21:57:09