gpt4 book ai didi

PHP 将数组转换为类内的对象。那可能吗?

转载 作者:可可西里 更新时间:2023-11-01 00:00:22 33 4
gpt4 key购买 nike

我有一个像

这样的变量
$a = array(
'first' => array( 'b' => 2, 'c' => 3),
'second' => array('d' => 4, 'e' => 5)
);

要访问一个元素,我可以使用

$a['first']['c']

但是要像这样访问它,

$a->first->c

我可以按如下方式将数组转换为对象:

$a = (object)array(
'first' => (object)array( 'b' => 2, 'c' => 3),
'second' => (object)array('d' => 4, 'e' => 5)
);

但我必须在这样的类中使用相同的内容..

class className {
public static $a = (object)array(
'first' => (object)array( 'b' => 2, 'c' => 3),
'second' => (object)array('d' => 4, 'e' => 5)
);
}

它抛出一个 T_OBJECT_CAST 错误。如果我想访问像

这样的元素,我怎样才能让它工作
className::$a->first->c;

最佳答案

Note that static member variable shares the memory among all objects of same class

你可以试试这个:

LIVE DEMO

<?php

class sample
{

public static $a;

function __construct() {

self::$a = (object)array(
'first' => (object)array( 'b' => 2, 'c' => 3),
'second' => (object)array('d' => 4, 'e' => 5)
);
}

}

// $obj = new sample();
var_dump(sample::$a->first);

关于PHP 将数组转换为类内的对象。那可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21546267/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com