PHP에서 stdClass는 무엇입니까?
무엇인지 정의하십시오 stdClass
.
stdClass
PHP의 일반적인 빈 클래스 Object
는 Java 또는 object
Python 과 같은 종류입니다 ( 편집 : 실제로 범용 기본 클래스로 사용되지는 않습니다 . 이 점 을 지적 해 주신 @Ciaran에게 감사드립니다 ).
익명 객체, 동적 속성 등에 유용합니다.
StdClass를 고려하는 쉬운 방법은 연관 배열의 대안입니다. json_decode()
StdClass 인스턴스 또는 연관 배열을 가져 오는 방법을 보여주는 아래 예제를 참조하십시오 . 또한이 예제에 표시되지 않은 SoapClient::__soapCall
StdClass 인스턴스를 반환합니다.
<?php
//Example with StdClass
$json = '{ "foo": "bar", "number": 42 }';
$stdInstance = json_decode($json);
echo $stdInstance->foo . PHP_EOL; //"bar"
echo $stdInstance->number . PHP_EOL; //42
//Example with associative array
$array = json_decode($json, true);
echo $array['foo'] . PHP_EOL; //"bar"
echo $array['number'] . PHP_EOL; //42
더 많은 예제 는 PHP 및 StdClass의 동적 속성을 참조하십시오 .
stdClass
다른 유형을 객체로 캐스팅 할 때 사용되는 일반적인 '빈'클래스입니다. 다른 두 답변이 말 했음에도 불구하고 PHP의 객체에 대한 기본 클래스 stdClass
가 아닙니다 . 이것은 매우 쉽게 증명할 수 있습니다.
class Foo{}
$foo = new Foo();
echo ($foo instanceof stdClass)?'Y':'N';
// outputs 'N'
PHP에 기본 개체의 개념이 있다고 생각하지 않습니다.
stdClass는 또 다른 훌륭한 PHP 기능입니다. 익명의 PHP 클래스를 만들 수 있습니다. 예를 들어 보겠습니다.
$page=new stdClass();
$page->name='Home';
$page->status=1;
이제 페이지 개체로 초기화하고 기본을 실행할 다른 클래스가 있다고 생각합니다.
<?php
class PageShow {
public $currentpage;
public function __construct($pageobj)
{
$this->currentpage = $pageobj;
}
public function show()
{
echo $this->currentpage->name;
$state = ($this->currentpage->status == 1) ? 'Active' : 'Inactive';
echo 'This is ' . $state . ' page';
}
}
이제 페이지 개체로 새 PageShow 개체를 만들어야합니다.
여기에 새로운 클래스 템플릿을 작성할 필요가 없습니다. stdClass를 사용하여 즉시 클래스를 만들 수 있습니다.
$pageview=new PageShow($page);
$pageview->show();
또한 주목할 가치가있는 것은 stdClass
객체를 사용하여 만들 수도 있다는 json_decode()
것입니다.
Using stdClass you can create a new object with it's own properties. Consider the following example that represents the details of a user as an associative array.
$array_user = array();
$array_user["name"] = "smith john";
$array_user["username"] = "smith";
$array_user["id"] = "1002";
$array_user["email"] = "smith@nomail.com";
If you need to represent the same details as the properties of an object, you can use stdClass as below.
$obj_user = new stdClass;
$obj_user->name = "smith john";
$obj_user->username = "smith";
$obj_user->id = "1002";
$obj_user->email = "smith@nomail.com";
If you are a Joomla developer refer this example in the Joomla docs for further understanding.
Likewise,
$myNewObj->setNewVar = 'newVal';
yields a stdClass object - auto casted
I found this out today by misspelling:
$GLOBASLS['myObj']->myPropertyObj->myProperty = 'myVal';
Cool!
stdClass is not an anonymous class or anonymous object
Answers here includes expressions that stdClass
is an anonymous class or even anonymous object. It's not a true.
stdClass
is just a regular predefined class. You can check this using instanceof
operator or function get_class
. Nothing special goes here. PHP uses this class when casting other values to object.
In many cases where stdClass
is used by the programmers the array is better option, because of useful functions and the fact that this usecase represents the data structure not a real object.
Actually I tried creating empty stdClass and compared the speed to empty class.
class emp{}
then proceeded creating 1000 stdClasses and emps... empty classes were done in around 1100 microseconds while stdClasses took over 1700 microseconds. So I guess its better to create your own dummy class for storing data if you want to use objects for that so badly (arrays are a lot faster for both writing and reading).
stdClass objects in use
The stdClass allows you to create anonymous classes and with object casting you can also access keys of an associative array in OOP style. Just like you would access the regular object property.
Example
class Example {
private $options;
public function __construct(Array $setup)
{
// casting Array to stdClass object
$this->options = (object) $setup;
// access stdClass object in oop style - here transform data in OOP style using some custom method or something...
echo $this->options->{'name'}; // ->{'key'}
echo $this->options->surname; // ->key
}
}
$ob1 = new Example(["name" => "John", "surname" => "Doe"]);
will echo
John Doe
Its also worth noting that by using Casting you do not actually need to create an object as in the answer given by @Bandula. Instead you can simply cast your array to an object and the stdClass is returned. For example:
$array = array(
'Property1'=>'hello',
'Property2'=>'world',
'Property3'=>'again',
);
$obj = (object) $array;
echo $obj->Property3;
Output: again
If you wanted to quickly create a new object to hold some data about a book. You would do something like this:
$book = new stdClass;
$book->title = "Harry Potter and the Prisoner of Azkaban";
$book->author = "J. K. Rowling";
$book->publisher = "Arthur A. Levine Books";
$book->amazon_link = "http://www.amazon.com/dp/0439136369/";
Please check the site - http://www.webmaster-source.com/2009/08/20/php-stdclass-storing-data-object-instead-array/ for more details.
Please bear in mind that 2 empty stdClasses are not strictly equal. This is very important when writing mockery expectations.
php > $a = new stdClass();
php > $b = new stdClass();
php > var_dump($a === $b);
bool(false)
php > var_dump($a == $b);
bool(true)
php > var_dump($a);
object(stdClass)#1 (0) {
}
php > var_dump($b);
object(stdClass)#2 (0) {
}
php >
php.net manual has a few solid explanation and examples contributed by users of what stdClass is, I especially like this one http://php.net/manual/en/language.oop5.basic.php#92123, https://stackoverflow.com/a/1434375/2352773.
stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.
When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.
stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.
You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.
stdclass is a way in which the php avoid stopping interpreting the script when there is some data must be put in a class , but unfortunately this class was not defined
Example :
return $statement->fetchAll(PDO::FETCH_CLASS , 'Tasks');
Here the data will be put in the predefined 'Tasks' . But, if we did the code as this :
return $statement->fetchAll(PDO::FETCH_CLASS );
then the php will put the results in stdclass .
simply php says that : look , we have a good KIDS[Objects] Here but without Parents . So , we will send them to a infant child Care Home stdclass :)
You can also use object
to cast arrays to an object of your choice:
Class Example
{
public $name;
public $age;
}
Now to create an object of type Example
and to initialize it you can do either of these:
$example = new Example();
$example->name = "some name";
$example->age = 22;
OR
$example = new Example();
$example = (object) ['name' => "some name", 'age' => 22];
The second method is mostly useful for initializing objects with many properties.
stClass is an empty class created by php itself , and should be used by php only, because it is not just an "empty" class , php uses stdClass to convert arrays to object style if you need to use stdClass , I recommend two better options : 1- use arrays (much faster than classes) 2- make your own empty class and use it
//example 1
$data=array('k1'=>'v1' , 'k2'=>'v2',....);
//example 2
//creating an empty class is faster than instances an stdClass
class data={}
$data=new data();
$data->k1='v1';
$data->k2='v2';
what makes someone to think about using the object style instead of array style???
참고URL : https://stackoverflow.com/questions/931407/what-is-stdclass-in-php
'Nice programing' 카테고리의 다른 글
Html.Partial 대 Html.RenderPartial & Html.Action 대 Html.RenderAction (0) | 2020.09.27 |
---|---|
새 탭 또는 창에서 링크 열기 (0) | 2020.09.27 |
HTTP POST 웹 요청을 만드는 방법 (0) | 2020.09.27 |
Google의 호스팅 된 jQuery를 사용하는 가장 좋은 방법이지만 Google의 호스팅 된 라이브러리로 대체 실패 (0) | 2020.09.27 |
30 분 후에 PHP 세션을 만료하려면 어떻게합니까? (0) | 2020.09.27 |