/
PHP 배열을 오브젝트 변환

PHP 배열을 오브젝트 변환

전달해야할 자료형은 오브젝트인데 배열을 전달할 경우 다음과 같은 에러가 발생함.

PHP Notice:  Trying to get property of non-object in

 

반대로 배열을 전달해야 하는데 오브젝트를 전달할 경우는 다음 에러 발생

PHP Fatal error:  Cannot use object of type stdClass as array in 

 

PHP 배열(array)을 오브젝트(object)로, 또는 오브젝트를 배열로 변환할 경우 캐스팅할 타입을 괄호로 둘러싸 주면 변환됨.

 

예제

<?php
 
$array = [ 'name' => 'My name', 'email' => 'myemail@example'];
 
echo $array['name'] . "\n";
 
// object 로 변환
$obj = (object) $array;
 
echo $obj ->name . "\n";
 
// 배열로 변환
$arr2 = (array) $obj;
 
echo $arr2['name'] . "\n";
?>

 

Ref

 

Related content

PHP 7 의 Scalar type declarations 과 declare(strict_types = 1) 구문
PHP 7 의 Scalar type declarations 과 declare(strict_types = 1) 구문
More like this
PHPStorm 에서 신규 소스 파일 생성시 declare(strict_types=1) 자동으로 붙이기
PHPStorm 에서 신규 소스 파일 생성시 declare(strict_types=1) 자동으로 붙이기
More like this
현대적인 PHP 프로그래밍(Modern PHP Programming)
현대적인 PHP 프로그래밍(Modern PHP Programming)
More like this
travis ci 에서 phpunit 에러날 때
travis ci 에서 phpunit 에러날 때
More like this
PHP 8 의 새로운 기능 - 특성(Attribute)
PHP 8 의 새로운 기능 - 특성(Attribute)
More like this
php 가 session 디렉터리에 쓰지 못할 때
php 가 session 디렉터리에 쓰지 못할 때
More like this