What are the two types of objects in php?

(*-*)浩
Release: 2023-02-23 17:54:02
Original
3056 people have browsed it

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();
?>
Copy after login

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; 
?>
Copy after login

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

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

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!

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!