相关疑难解决方法(0)

PHP从对象打印键?

我有一个对象BIRD然后有[0]到[10]并且每个数字都有一个像"bug"或"beetle"或"gnat"这样的子标题以及每个数字的值.

我想要打印

BIRD 
    [0]
       bug = > value 
Run Code Online (Sandbox Code Playgroud)

我无法在任何地方找到如何做到这一点 - 有关于PUBLIC和PRIVATE和CLASS的讨论,这就是我脱落的地方

php arrays object echo

18
推荐指数
3
解决办法
5万
查看次数

PHP中的数组到Object和Object to Array - 有趣的行为

你能解释下一个有趣的行为吗?

class test {
  //Class *test* has two properties, public and private.
  public $xpublic = 'x1';
  private $xprivate = 'x2';
}
$testObj = new test();
Run Code Online (Sandbox Code Playgroud)

让我们转换$testObj为数组.

settype($testObj, 'array');
var_dump($testObj);
Run Code Online (Sandbox Code Playgroud)

结果:

array(2) {
  ["xpublic"]=> string(3) "x1"
  ["testxprivate"]=> string(4) "x2"
}

好的,xprivate财产变成了testxprivate

让我们将这个数组转换为object.

$newObj = (object)$testObj;
var_dump($newObj);
Run Code Online (Sandbox Code Playgroud)

结果:

object(stdClass)#1 (2) {
  ["xpublic"]=> string(3) "xxx"
  ["xprivate":"test":private]=> string(4) "xxx3"
}

$newObj是一个stdClass对象.

问题是:

为什么testxprivate成为新对象的私有财产xprivate(而不是testxprivate)?PHP如何知道该$testObj数组是一个对象?

如果我定义相等的数组:

$testArray = array('xpublic'=>'x1', 'testxprivate'=>'x2'); …
Run Code Online (Sandbox Code Playgroud)

php arrays casting object

18
推荐指数
1
解决办法
2234
查看次数

PHP未定义的数组索引.为什么?

这是......我甚至不知道这是怎么回事.

// var_dump of items before
object(stdClass)[84]
   public '75' => object(stdClass)[87]

$items = (array) $items; // Casting unserialized stdClass to array
var_dump($items);

//Result of var dump:
array
  '75' => 
    object(stdClass)[87]

//Now lets get this item:
var_dump($items[75]); // Error
var_dump($items['75']); // Error
Run Code Online (Sandbox Code Playgroud)

什么?

谢谢.

php arrays

9
推荐指数
1
解决办法
1386
查看次数

如何在PHP中将对象转换为关联数组?

正如标题所示,我的问题是我如何将php类转换为关联数组?比如我

class MyObject {
  private $size = null;
  private $length = null;
  private $width = null;

    public function getSize(){
        return $this->size;
    }

    public function setSize($size){
        $this->size = $size;
    }

    public function getLength(){
        return $this->length;
    }

    public function setLength($length){
        $this->length = $length;
    }

    public function getWidth(){
        return $this->width;
    }

    public function setWidth($width){
        $this->width = $width;
    }

}

//Now what i want is following

$abc = new MyObject();
$abc->width = 10;
$anArray = someFunction($abc);  
//This should generate an associative array
//Now associative …
Run Code Online (Sandbox Code Playgroud)

php

2
推荐指数
1
解决办法
2480
查看次数

标签 统计

php ×4

arrays ×3

object ×2

casting ×1

echo ×1