Home > Backend Development > PHP Tutorial > How to access the properties of an object in php

How to access the properties of an object in php

怪我咯
Release: 2023-03-11 20:58:01
Original
7608 people have browsed it

php Method to access the attribute of the object (when the key name of the attribute is a number) {}

This article writes a way to ArrayMethod to convert into an object. The keys of this array are numbers (that is, the array is an indexarray). When accessing the object, $obj->1 is obviously misplaced. So what should we do? What about accessing numeric properties of an object?

$obj->{1} ; Represents the attribute value corresponding to the key 1 of the attribute of the access object $obj!

<?php
/**
 * Created by PhpStorm.
 * User: FLY.YUAN
 * Date: 16-6-14
 * Time: 下午2:26
 */
 
 function toObject($array)
{
    //$o = (object)&#39;&#39;;
    $o = new \stdClass();
 
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $value = toObject($value);
        }
 
        $o->$key = $value;
    }
 
    return $o;
}
$obj = toObject(array( array(1=>23)));
echo "<pre class="brush:php;toolbar:false">";
//JSON encode, and then decode your object passing true as the second param in the decode function.
//This will return an associative array.
//var_dump(json_decode(json_encode($obj), true));
var_dump($obj->{0}->{1});
 
$a = array(&#39;123&#39; => &#39;123&#39;, &#39;123foo&#39; => &#39;123foo&#39;);
$o = json_decode(json_encode($a), true);
var_dump($o);
 
function recursive_cast_to_array($o) {
    $a = (array)$o;
    foreach ($a as &$value) {
        if (is_object($value)) {
            $value = recursive_cast_to_array($value);
        }
    }
 
    return $a;
}
$myVar = toObject(array(&#39;highlighting&#39; => array(&#39;448364&#39; => array(&#39;Data&#39; => array(123)))));
$arr = recursive_cast_to_array($myVar);
echo 134;
var_dump( $myVar->highlighting->{448364}->Data->{0});
 
var_dump(NULL == false);
 
$test = array();
$test[&#39;$.router&#39;] = 123;
var_dump($test);
Copy after login

The above is the detailed content of How to access the properties of an object in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template