1
0
mirror of https://github.com/php/doc-zh.git synced 2026-03-24 07:02:15 +01:00
Files
archived-doc-zh/language/types/object.xml
2025-11-30 00:42:55 +08:00

105 lines
2.4 KiB
XML

<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<!-- EN-Revision: e587d0655e426f97b3fcb431453da5030e743b23 Maintainer: Altair Status: ready -->
<!-- CREDITS: Geogory, dallas, Luffy, mowangjuanzi -->
<sect1 xml:id="language.types.object">
<title>Object 对象</title>
<sect2 xml:id="language.types.object.init">
<title>对象初始化</title>
<para>
要创建新的 <type>object</type>,使用 <literal>new</literal> 语句实例化类:
</para>
<example>
<title>对象构造</title>
<programlisting role="php">
<![CDATA[
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
?>
]]>
</programlisting>
</example>
<simpara>
详细讨论参见手册中<link linkend="language.oop5">类与对象</link>章节。
</simpara>
</sect2>
<sect2 xml:id="language.types.object.casting">
<title>转换为对象</title>
<para>
如果将一个对象转换成对象,它将不会有任何变化。如果其它任何类型的值被转换成对象,将会创建一个内置类
<classname>stdClass</classname> 的实例。如果该值为
&null;,则新的实例为空。
<type>array</type> 转换成 <type>object</type> 将使键名成为属性名并具有相对应的值。注意:在这个例子里, 使用 PHP 7.2.0 之前的版本,数字键只能通过迭代访问。
</para>
<example>
<title>Casting to an Object</title>
<programlisting role="php">
<![CDATA[
<?php
$obj = (object) array('1' => 'foo');
var_dump(isset($obj->{'1'})); // 输出 'bool(true)'
// 自 PHP 8.1 起弃用
var_dump(key($obj)); // 输出 'string(1) "1"'
?>
]]>
</programlisting>
</example>
<para>
对于其他值,会包含进成员变量名 <literal>scalar</literal>
</para>
<example>
<title><literal>(object)</literal> cast</title>
<programlisting role="php">
<![CDATA[
<?php
$obj = (object) 'ciao';
echo $obj->scalar; // 输出 'ciao'
?>
]]>
</programlisting>
</example>
</sect2>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->