Home  >  Article  >  Backend Development  >  What are the two types of objects in php?

What are the two types of objects in php?

(*-*)浩
(*-*)浩Original
2019-09-06 11:24:233098browse

What are the two types of objects in php?

Built-in objects: provided by PHP, do not depend on the host environment objects, these objects already exist before the program is executed. That is, built-in objects exist in any environment.

Custom objects: As the name suggests, they are objects defined by developers themselves. PHP allows the use of custom objects to expand PHP applications and functions

Object initialization (Recommended learning: PHP programming from entry to proficiency)

To create a new object object, use the new statement to instantiate a class:

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo."; 
    }
}

$bar = new foo;
$bar->do_foo();
?>

Convert to object

If you convert an object to an object, it will not change in any way. If a value of any other type is converted to an object, an instance of the built-in class stdClass will be created.

If the value is NULL, the new instance is empty. Converting array to object will make the key name a property name with corresponding value.

Note: In this example, using versions prior to PHP 7.2.0, the numeric keys can only be accessed via iteration.

<?php
$obj = (object) array(&#39;1&#39; => &#39;foo&#39;);
var_dump(isset($obj->{&#39;1&#39;})); // PHP 7.2.0 后输出 &#39;bool(true)&#39;,之前版本会输出 &#39;bool(false)&#39; 
var_dump(key($obj)); // PHP 7.2.0 后输出 &#39;string(1) "1"&#39;,之前版本输出  &#39;int(1)&#39; 
?>

For other values, the member variable name scalar will be included.

<?php
$obj = (object) &#39;ciao&#39;;
echo $obj->scalar;  // outputs &#39;ciao&#39;
?>

The above is the detailed content of What are the two types of objects in php?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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