cvs: phpdoc-ru /language types.xml
| From: | Kai Liki | Date: | Tue, 14 Jan 2003 14:32:15 +0000 |
| Subject: | cvs: phpdoc-ru /language types.xml | ||
| Groups: | php.doc.ru | ||
| Request: | Send a blank email to doc-ru+get-69@lists.php.net to get a copy of this message | ||
kai Tue Jan 14 09:32:15 2003 EDT
Added files:
/phpdoc-ru/language types.xml
Log:
More than 1/3 translated
Index: phpdoc-ru/language/types.xml +++ phpdoc-ru/language/types.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- EN-Revision: 1.98 Maintainer: Kai Status: ready --> <!-- $Revision: 1.1 $ --> <chapter id="language.types"> <title>Òèïû</title> <!-- Çàìå÷àíèå: Ïîñëåäíåå èçìåíåíèå çàìåòêè: 2003-09-01 resource ïåðåâåë êàê èñòî÷íèê control structure = óïðàâëÿþùàÿ êîíñòðóêöèÿ language.types.string.conversion = Êîíâåðòàöèÿ ñòðîê â ÷èñëà Arbitrary Precision Mathematics Functions=ìàòåìàòè÷åñêèå ôóêöèè ïðîèçâîëüíîé òî÷íîñòè String conversion to numbers = Êîíâåðòàöèÿ ñòðîê â ÷èñëà language.types.integer.casting = è äðóãèå ññûëêè - óòî÷íèòü heredoc-ñèíòàêñèñ - êàê ïåðåâåñòè? Escaped characters --> <sect1 id="language.types.intro"> <title>Ââåäåíèå</title> <simpara> PHP ïîääåðæèâàåò âîñåìü ïðîñòûõ òèïîâ. </simpara> <para> ×åòûðå ñêàëÿðíûõ òèïà: <itemizedlist> <listitem> <simpara> <link linkend="language.types.boolean">áóëåâ</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.integer">öåëîå</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.float">÷èñëî ñ ïëàâàþùåé òî÷êîé</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.string">ñòðîêà</link> </simpara> </listitem> </itemizedlist> Äâà ñìåøàííûõ òèïà: <itemizedlist> <listitem> <simpara> <link linkend="language.types.array">ìàññèâ</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.object">îáúåêò</link> </simpara> </listitem> </itemizedlist> È, íàêîíåö, äâà ñïåöèàëüíûõ òèïà: <itemizedlist> <listitem> <simpara> <link linkend="language.types.resource">èñòî÷íèê</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.null">NULL</link> </simpara> </listitem> </itemizedlist>  ýòîé äîêóìåíòàöèè òàêæå ïðåäñòàâëåíî íåñêîëüêî <link linkend="language.pseudo-types">ïñåâäî-òèïîâ</link> äëÿ óäîáñòâà ïîíèìàíèÿ: <itemizedlist> <listitem> <simpara> <link linkend="language.types.mixed">ñìåøàííûé</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.number">÷èñëî</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.mixed">îáðàòíûé âûçîâ (callback)</link> </simpara> </listitem> </itemizedlist> Âû òàêæå ìîæåòå íàéòè íåñêîëüêî óïîìèíàíèé òèïà äâîéíîé òî÷íîñòè. Ðàññìàòðèâàéòå åãî êàê ÷èñëî ñ ïëàâàþùåé òî÷êîé, äâà èìåíè ñóùåñòâóþò òîëüêî ïî èñòîðè÷åñêèì ïðè÷èíàì. </para> <simpara> Êàê ïðàâèëî, ïðîãðàììèñò íå óñòàíàâëèâàåò òèï ïåðåìåííîé; ïðåäïî÷òèòåëüíåå, ÷òîáû ýòî äåëàë PHP âî âðåìÿ âûïîëíåíèÿ ïðîãðàììû â çàâèñèìîñòè îò êîíòåêñòà, â êîòîðîì èñïîëüçóåòñÿ ïåðåìåííàÿ. </simpara> <note> <simpara> Åñëè âû æåëàåòå ïðîâåðèòü òèï è çíà÷åíèå îïðåäåëåííîãî <link linkend="language.expressions">âûðàæåíèÿ</link>, èñïîëüçóéòå <function>var_dump</function>. </simpara> <para> Åñëè æå âàì äëÿ îòëàäêè íåîáõîäèìî ïðîñòî óäîáî÷èòàåìîå ïðåäñòàâëåíèå òèïà, èñïîëüçóéòå <function>gettype</function>. ×òîáû ïðîâåðèòü íà îïðåäåëåííûé òèï, <emphasis>íå</emphasis> èñïîëüçóéòå <function>gettype</function>, ïðèìåíÿéòå äëÿ ýòîãî <literal>is_<replaceable>type</replaceable></literal> ôóíêöèè. Âîò íåñêîëüêî ïðèìåðîâ: <informalexample> <programlisting role="php"> <![CDATA[ $bool = TRUE; // ëîãè÷åñêèé $str = "foo"; // ñòðîêîâûé $int = 12; // öåëî÷èñëåííûé echo gettype($bool); // âûâîäèò "boolean" echo gettype($str); // âûâîäèò "string" // Åñëè ýòî öåëîå, óâåëè÷èòü íà ÷åòûðå if (is_int($int)) { $int += 4; } // Åñëè $bool - ýòî ñòðîêà, âûâåñòè åå // (íè÷åãî íå âûâîäèò) if (is_string($bool)) { echo "Ñòðîêà: $bool"; } ]]> </programlisting> </informalexample> </para> </note> <simpara> Åñëè âû õîòèòå ïðèíóäèòåëüíî èçìåíèòü òèï ïåðåìåííîé, âû ìîæåòå ëèáî <link linkend="language.types.typecasting">ïðèâåñòè</link> ïåðåìåííóþ, ëèáî èñïîëüçîâàòü ôóíêöèþ <function>settype</function>. </simpara> <simpara> Îáðàòèòå âíèìàíèå, ÷òî ïåðåìåííàÿ, â çàâèñèìîñòè îò åå òèïà â äàííûé ìîìåíò, â îïðåäåëåííûõ ñèòóàöèÿõ ìîæåò èìåòü ðàçíûå çíà÷åíèÿ. Áîëåå ïîäðîáíóþ èíôîðìàöèþ ñìîòðèòå â ðàçäåëå <link linkend="language.types.type-juggling">Ìàíèïóëÿöèè ñ òèïàìè</link>. </simpara> </sect1> <sect1 id="language.types.boolean"> <title>Áóëåâ</title> <simpara> Ýòî ïðîñòåéøèé òèï. Îí âûðàæàåò èñòèííîñòü çíà÷åíèÿ - ýòî ìîæåò áûòü ëèáî &true;, ëèáî &false;. </simpara> <note> <simpara> Áóëåâ òèï áûë ââåäåí â PHP 4. </simpara> </note> <sect2 id="language.types.boolean.syntax"> <title>Ñèíòàêñèñ</title> <para> ×òîáû îïðåäåëèòü áóëåâ òèï, èñïîëüçóéòå êëþ÷åâîå ñëîâî &true; èëè &false;. Îáà ðåãèñòðî-íåçàâèñèìû. <informalexample> <programlisting role="php"> <![CDATA[ $foo = True; // îïðåäåëèòü $foo êàê TRUE ]]> </programlisting> </informalexample> </para> <para> Îáû÷íî âû èñïîëüçóåòå íåêèé <link linkend="language.operators">îïåðàòîð</link>, êîòîðûé âîçâðàùàåò ëîãè÷åñêîå âûðàæåíèå, à çàòåì ïðåäàåò åãî <link linkend="control-structures">óïðàâëÿþùåé êîíñòðóêöèè</link>. <informalexample> <programlisting role="php"> <![CDATA[ // == ýòî îïåðàòîð, êîòîðûé ïðîâåðÿåò // ýêâèâàëåíòíîñòü è âîçâðàùàåò áóëåâî çíà÷åíèå if ($action == "ïîêàçàòü_âåðñèþ") { echo "Âåðñèÿ 1.23"; } // ýòî íå îáÿçàòåëüíî... if ($show_separators == TRUE) { echo "<hr>\n"; } // ...ïîòîìó ÷òî âû ìîæåòå ïðîñòî íàïèñàòü if ($show_separators) { echo "<hr>\n"; } ]]> </programlisting> </informalexample> </para> </sect2> <sect2 id="language.types.boolean.casting"> <title>Êîíâåðòàöèÿ â áóëåâ òèï</title> <simpara> Äëÿ íåñîìíåííîé êîíâåðòàöèè çíà÷åíèÿ â áóëåâ òèï èñïîëüçóéòå ïðèâèäåíèå òèïà <literal>(bool)</literal> èëè <literal>(boolean)</literal>. Îäíàêî â áîëüøèíñòâå ñëó÷àåâ âàì íåò íåîáõîäèìîñòè èñïîëüçîâàòü ïðèâèäåíèå òèïà, ïîñêîëüêó çíà÷åíèå áóäåò àâòîìàòè÷åñêè êîíâåðòèðîâàíî, åñëè îïåðàòîð, ôóíêöèÿ èëè óïðàâëÿþùàÿ êîíñòðóêöèÿ òðåáóåò áóëåâ àðãóìåíò. </simpara> <simpara> Ñìîòðèòå òàêæå <link linkend="language.types.type-juggling">Ìàíèïóëÿöèè ñ òèïàìè</link>. </simpara> <para> Ïðè êîíâåðòàöèè â ëîãè÷åñêèé òèï, ñëåäóþùèå çíà÷åíèÿ ðàññìàòðèâàþòñÿ êàê &false;: <itemizedlist> <listitem> <simpara>Ñàì <link linkend="language.types.boolean">áóëåâ</link> &false;</simpara> </listitem> <listitem> <simpara><link linkend="language.types.integer">öåëîå</link > 0 (íîëü) </simpara> </listitem> <listitem> <simpara><link linkend="language.types.float">÷èñëî ñ ïëàâàþùåé òî÷êîé</link> 0.0 (íîëü) </simpara> </listitem> <listitem> <simpara>ïóñòàÿ <link linkend="language.types.string" >ñòðîêà</link> è <link linkend="language.types.string" >ñòðîêà</link> "0"</simpara> </listitem> <listitem> <simpara><link linkend="language.types.array">ìàññèâ</link> ñ íóëåâûìè ýëåìåíòàìè</simpara> </listitem> <listitem> <simpara><link linkend="language.types.object">îáúåêò</link> ñ íóëåâûìè ïåðåìåííûìè-÷ëåíàìè</simpara> </listitem> <listitem> <simpara>ñïåöèàëüíûé òèï <link linkend="language.types.null" >NULL</link> (âêëþ÷àÿ íåóñòàíîâëåííûå ïåðåìåííûå) </simpara> </listitem> </itemizedlist> Âñå îñòàëüíûå çíà÷åíèÿ ðàññìàòðèâàþòñÿ êàê &true; (âêëþ÷àÿ ëþáîé <link linkend="language.types.resource">èñòî÷íèê</link>). <warning> <simpara> <literal>-1</literal> ñ÷èòàåòñÿ &true;, êàê è ëþáîå íåíóëåâîå (îòðèöàòåëüíîå èëè ïîëîæèòåëüíîå) ÷èñëî! </simpara> </warning> <informalexample> <programlisting role="php"> <![CDATA[ echo gettype((bool) ""); // bool(false) echo gettype((bool) 1); // bool(true) echo gettype((bool) -2); // bool(true) echo gettype((bool) "foo"); // bool(true) echo gettype((bool) 2.3e5); // bool(true) echo gettype((bool) array(12)); // bool(true) echo gettype((bool) array()); // bool(false) ]]> </programlisting> </informalexample> </para> </sect2> </sect1> <sect1 id="language.types.integer"> <title>Öåëûå</title> <simpara> Öåëîå ýòî ÷èñëî èç ìíîæåñòâà Z = {..., -2, -1, 0, 1, 2, ...}. </simpara> <para> Ñìîòðèòå òàêæå: <link linkend="ref.gmp">Öåëûå ïðîèçâîëüíîé äëèíû</link> è <link linkend="language.types.float">×èñëà ñ ïëàâàþùåé òî÷êîé</link> </para> <sect2 id="language.types.integer.syntax"> <title>Ñèíòàêñèñ</title> <simpara> Öåëûå ìîãóò áûòü óêàçàíû â äåñÿòè÷íîé, øåñòíàäöàòåðè÷íîé èëè âîñüìåðè÷íîé ñèñòåìå ñ÷èñëåíèÿ, ïî æåëàíèþ ñ ïðåäøåñòâóþùèì çíàêîì (- èëè +). </simpara> <para> Åñëè âû èñïîëüçóåòå âîñüìåðè÷íóþ ñèñòåìó ñ÷èñëåíèÿ, âû äîëæíû ïðåäâàðèòü ÷èñëî <literal>0</literal> (íóëåì), äëÿ èñïîëüçîâàíèÿ øåñòíàäöàòåðè÷íîé ñèñòåìû íóæíî ïîñòàâèòü ïåðåä ÷èñëîì <literal>0x</literal>. <example> <title>Öåëûå</title> <programlisting role="php"> <![CDATA[ $a = 1234; # äåñÿòè÷íîå ÷èñëî $a = -123; # îòðèöàòåëüíîå ÷èñëî $a = 0123; # âîñüìåðè÷íîå ÷èñëî (ýêâèâàëåíòíî 83 â äåñÿòè÷íîé ñèñòåìå) $a = 0x1A; # øåñòíàäöàòåðè÷íîå ÷èñëî (ýêâèâàëåíòíî 26 â äåñÿòè÷íîé ñèñòåìå) ]]> </programlisting> </example> Ôîðìàëüíî âîçìîæíàÿ ñòðóêòóðà öåëûõ òàêîâà: <informalexample> <programlisting> <![CDATA[ äåñÿòè÷íûå : [1-9][0-9]* | 0 øåñòíàäöàòåðè÷íûå : 0[xX][0-9a-fA-F]+ âîñüìåðè÷íûå : 0[0-7]+ öåëûå : [+-]?äåñÿòè÷íûå | [+-]?øåñòíàäöàòåðè÷íûå | [+-]?âîñüìåðè÷íûå ]]> </programlisting> </informalexample> Ðàçìåð öåëîãî çàâèñèò îò ïëàòôîðìû, õîòÿ, êàê ïðàâèëî, ìàêñèìàëüíîå çíà÷åíèå îêîëî äâóõ ìèëëèàðäîâ (ýòî 32-áèòíîå çíàêîâîå). PHP íå ïîääåðæèâàåò áåççíàêîâûå öåëûå. </para> </sect2> <sect2 id="language.types.integer.overflow"> <title>Ïðåâûøåíèå ðàçìåðà öåëîãî</title> <para> Åñëè âû îïðåäåëèòå ÷èñëî, ïðåâûøàþùåå ïðåäåëû öåëîãî òèïà, îíî áóäåò èíòåðïðåòèðîâàíî êàê ÷èñëî ñ ïëàâàþùåé òî÷êîé. Òàêæå, åñëè âû èñïîëüçóåòå îïåðàòîð, ðåçóëüòàòîì ðàáîòû êîòîðîãî áóäåò ÷èñëî, ïðåâûøàþùåå ïðåäåëû öåëîãî, âìåñòî íåãî áóäåò âîçâðàùåíî ÷èñëî ñ ïëàâàþùåé òî÷êîé. <informalexample> <programlisting role="php"> <![CDATA[ $large_number = 2147483647; var_dump($large_number); // âûâîä: int(2147483647) $large_number = 2147483648; var_dump($large_number); // âûâîä: float(2147483648) // ýòî ñïðàâåäëèâî è äëÿ øåñòíàäöàòåðè÷íûõ öåëûõ: var_dump( 0x80000000 ); // âûâîä: float(2147483648) $million = 1000000; $large_number = 50000 * $million; var_dump($large_number); // âûâîä: float(50000000000) ]]> </programlisting> </informalexample> <warning> <simpara> Ê ñîæàëåíèþ, â PHP áûëà îøèáêà, òàê ÷òî ýòî íå âñåãäà âåðíî ðàáîòàåò, êîãäà èñïîëüçóþòñÿ îòðèöàòåëüíûå ÷èñëà. Íàïðèìåð: êîãäà âû óìíîæàåòå <literal>-50000 * $million</literal>, ðåçóëüòàòîì áóäåò <literal>-429496728</literal>. Îäíàêî, åñëè îáà îïåðàíäà ïîëîæèòåëüíû, ïðîáëåì íå âîçíèêàåò. </simpara> <simpara> Ýòà îøèáêà óñòðàíåíà â PHP 4.1.0. </simpara> </warning> </para> <para> â PHP íå ñóùåñòâóåò îïåðàòîðà äåëåíèÿ öåëûõ. Ðåçóëüòàòîì <literal>1/2</literal> áóäåò ÷èñëî ñ ïëàâàþùåé òî÷êîé <literal>0.5</literal>. Âû ìîæåòå ïðèâåñòè çíà÷åíèå ê öåëîìó, ÷òî âñåãäà îêðóãëÿåò åãî â ìåíüøóþ ñòîðîíó, ëèáî èñïîëüçîâàòü ôóíêöèþ <function>round</function>. <informalexample> <programlisting role="php"> <![CDATA[ var_dump(25/7); // float(3.5714285714286) var_dump((int) (25/7)); // int(3) var_dump(round(25/7)); // float(4) ]]> </programlisting> </informalexample> </para> </sect2> <sect2 id="language.types.integer.casting"> <title>Êîíâåðòàöèÿ â öåëîå</title> <simpara> Äëÿ íåñîìíåííîé êîíâåðòàöèè çíà÷åíèÿ â öåëîå èñïîëüçóéòå ïðèâèäåíèå òèïà <literal>(int)</literal> èëè <literal>(integer)</literal>. Îäíàêî â áîëüøèíñòâå ñëó÷àåâ âàì íåò íåîáõîäèìîñòè èñïîëüçîâàòü ïðèâèäåíèå òèïà, ïîñêîëüêó çíà÷åíèå áóäåò àâòîìàòè÷åñêè êîíâåðòèðîâàíî, åñëè îïåðàòîð, ôóíêöèÿ èëè óïðàâëÿþùàÿ êîíñòðóêöèÿ òðåáóåò öåëûé àðãóìåíò. Âû òàêæå ìîæåòå êîíâåðòèðîâàòü çíà÷åíèå â öåëîå ïðè ïîìîùè ôóíêöèè <function>intval</function>. </simpara> <simpara> Ñìîòðèòå òàêæå <link linkend="language.types.type-juggling">Ìàíèïóëÿöèè ñ òèïàìè</link>. </simpara> <sect3 id="language.types.integer.casting.from-boolean"> <title>Èç <link linkend="language.types.boolean" >áóëåâà</link> òèïà</title> <simpara> &false; êîíâåðòèðóåòñÿ â <literal>0</literal> (íîëü), à &true; - â <literal>1</literal> (åäèíèöó). </simpara> </sect3> <sect3 id="language.types.integer.casting.from-float"> <title>Èç <link linkend="language.types.float">÷èñåë ñ ïëàâàþùåé òî÷êîé</link></title> <simpara> Ïðè êîíâåðòàöèè èç ÷èñëà ñ ïëàâþùåé òî÷êîé â öåëîå, ÷èñëî áóäåò îêðóãëåíî <emphasis>â ñòîðîíó íóëÿ</emphasis>. </simpara> <para> Åñëè ÷èñëî ñ ïëàâàþùåé òî÷êîé ïðåâûøàåò ïðåäåëû öåëîãî (êàê ïðàâèëî, ýòî <literal>+/- 2.15e+9 = 2^31</literal>), ðåçóëüòàò áóäåò íåîïðåäåë¸ííûì, òàê êàê öåëîå íå èìååò äîñòàòî÷íîé òî÷íîñòè, ÷òîáû âåðíóòü âåðíûé ðåçóëüòàò.  ýòîì ñëó÷àå íå áóäåò âûâåäåíî íè ïðåäóïðåæäåíèÿ, íè äàæå çàìå÷àíèÿ! </para> <warning><para> Íèêîãäà íå ïðèâîäèòå íåèçâåñòíóþ äðîáü ê öåëîìó, òàê êàê ýòî ìîæåò èíîãäà äàòü íåîæèäàííûå ðåçóëüòàòû. <informalexample> <programlisting role="php"> <![CDATA[ echo (int) ( (0.1+0.7) * 10 ); // âûâîäèò 7! ]]> </programlisting> </informalexample> Ñìîòðèòå áîëåå ïîäðîáíî: <link linkend="warn.float-precision">ïðåäóïðåæäåíèå î òî÷íîñòè ÷èñëåë ñ ïëàâàþùåé òî÷êîé</link>. </para></warning> </sect3> <sect3 id="language.types.integer.casting.from-string"> <title>Èç ñòðîê</title> <simpara> Ñìîòðèòå <link linkend="language.types.string.conversion">Êîíâåðòàöèÿ ñòðîê â ÷èñëà</link> </simpara> </sect3> <sect3 id="language.types.integer.casting.from-other"> <title>Èç äðóãèõ òèïîâ</title> <para> <caution> <simpara> Äëÿ äðóãèõ òèïîâ ïîâåäåíèå êîíâåðòàöèè â öåëîå íå îïðåäåëåíî.  íàñòîÿùåå âðåìÿ ïîâåäåíèå òàêîå æå, êàê åñëè áû çíà÷åíèå ñïåðâà áûëî <link linkend="language.types.boolean.casting" >êîíâåðòèðîâàíî â áóëåâ òèï</link>. Îäíàêî <emphasis>íå</emphasis> ïîëàãàéòåñü íà ýòî ïîâåäåíèå, òàê êàê îí ìîæåò èçìåíèòüñÿ áåç ïðåäóïðåæäåíèÿ. </simpara> </caution> </para> </sect3> </sect2> </sect1> <sect1 id="language.types.float"> <title>×èñëà ñ ïëàâþùåé òî÷êîé</title> <para> ×èñëà ñ ïëàâþùåé òî÷êîé (îíè æå ÷èñëà äâîéíîé òî÷íîñòè èëè äåéñòâèòåëüíûå ÷èñëà) ìîãóò áûòü îïðåäåëåíû ïðè ïîìîùè ëþáîãî èç ñëåäóþùèõ ñèíòàêñèñîâ: <informalexample> <programlisting role="php"> $a = 1.234; $a = 1.2e3; $a = 7E-10; </programlisting> </informalexample> Ôîðìàëüíî: <informalexample> <programlisting role="php"> LNUM [0-9]+ DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*) EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM}) </programlisting> </informalexample> Ðàçìåð öåëîãî çàâèñèò îò ïëàòôîðìû, õîòÿ ìàêñèìóì, êàê ïðàâèëî, ~1.8e308 ñ òî÷íîñòüþ îêîëî 14 äåñÿòè÷íûõ öèôð (ýòî 64-áèòíûé IEEE-ôîðìàò). </para> <warning id="warn.float-precision"> <title>Òî÷íîñòü ÷èñëà ñ ïëàâàþùåé òî÷êîé</title> <para> Äîâîëüíî ÷àñòî ïðîñòûå äåñÿòè÷íûå äðîáè âðîäå <literal>0.1</literal> èëè <literal>0.7</literal> íå ìîãóò áûòü êîíâåðòèðîâàíû â ñâîè âíóòðåííèå äâîè÷íûå àíàëîãè áåç íåáîëüøîé ïîòåðè òî÷íîñòè. Ýòî ìîæåò ïðèâåñòè ê íåîæèäàííûì ðåçóëüòàòàì: íàïðèìåð, <literal>floor((0.1+0.7)*10)</literal> ñêîðåå âñåãî âîçâðàòèò <literal>7</literal> âìåñòî îæèäàåìîé <literal>8</literal> êàê ðåçóëüòàò âíóòðåííåãî ïðåäñòàâëåíèÿ ÷èñëà, ÿâëÿþùåãîñÿ â äåéñòâèòåëüíîñòè ÷åì-òî âðîäå <literal>7.9999999999...</literal>. </para> <para> Ýòî ñâÿçàíî ñ íåâîçìîæíîñòüþ òî÷íî âûðàçèòü íåêîòîðûå äðîáè â äåñÿòè÷íîé ñèñòåìå ñ÷èñëåíèÿ êîíå÷íûì ÷èñëîì öèôð. Íàïðèìåð, <literal>1/3</literal> â äåñÿòè÷íîé ôîðìå ïðèíèìàåò âèä <literal>0.3333333. . .</literal>. </para> <para> Òàê ÷òî íèêîãäà íå äîâåðÿéòå òî÷íîñòè ïîñëåäíèõ öèôð â ðåçóëüòàòàõ ñ ÷èñëàìè ñ ïëàâàþùåé òî÷êîé è íèêîãäà íå ïðîâåðÿéòå èõ íà ðàâåíñòâî. Åñëè âàì äåéñâèòåëüíî íåîáõîäèìà âûñîêàÿ òî÷íîñòü, âàì ñëåäóåò èñïîëüçîâàòü <link linkend="ref.bc">ìàòåìàòè÷åñêèå ôóíêöèè ïðîèçâîëüíîé òî÷íîñòè</link> èëè <link linkend="ref.gmp">gmp</link>-ôóíêöèè. </para> </warning> <sect2 id="language.types.float.casting"> <title>Êîíâåðòàöèÿ â ÷èñëî ñ ïëàâàþùåé òî÷êîé</title> <para> Î òîì êîãäà è êàê ñòðîêè êîíâåðòèðóþòñÿ â ÷èñëà ñ ïëàâàþùåé òî÷êîé ÷èòàéòå â ðàçäåëå <link linkend="language.types.string.conversion">Êîíâåðòàöèÿ ñòðîê â ÷èñëà</link>. Äëÿ çíà÷åíèé äðóãèõ òèïîâ êîíâåðòàöèÿ áóäåò òàêîé æå, êàê åñëè áû çíà÷åíèå ñíà÷àëà áûëî êîíâåðòèðîâàíî â öåëîå, à çàòåì â ÷èñëî ñ ïëàâàþùåé òî÷êîé. Äîïîëíèòåëüíóþ èíôîðìàöèþ ñìîòðèòå â ðàçäåëå <link linkend="language.types.integer.casting">Êîíâåðòàöèÿ â öåëîå</link>. </para> </sect2> </sect1> <sect1 id="language.types.string"> <title>Ñòðîêè</title> <para> Ñòðîêà - ýòî íàáîð ñèìâîëîâ.  PHP ñèìâîë ýòî òî æå ñàìîå, ÷òî è áàéò, ýòî çíà÷èò, ÷òî âîçìîæíî ðîâíî 256 ðàçëè÷íûõ ñèìâîëîâ. Ýòî òàêæå îçíà÷àåò, ÷òî PHP íå èìååò âñòðîåííîé ïîääåðæêè Unicode'à. Íåêîòîðóþ ïîääåðæêó Unicode'à îáåñïå÷èâàþò ýòè ôóíêöèè <function>utf8_enncode</function> è <function>utf8_decode</function>. </para> <note> <simpara> Íåò íèêàêèõ ïðîáëåì, åñëè ñòðîêà î÷åíü âåëèêà. Ïðàêòè÷åñêè íå ñóùåñòâóåò îãðàíè÷åíèé íà ðàçìåð ñòðîê, íàëàãàåìûõ PHP, òàê ÷òî íåò àáñîëþòíî íèêàêèõ ïðè÷èí áåñïîêîèòüñÿ îá èõ äëèíå. </simpara> </note> <sect2 id="language.types.string.syntax"> <title>Ñèíòàêñèñ</title> <para> Ñòðîêà ìîæåò áûòü îïðåäåëåíà òðåìÿ ðàçëè÷íûìè ñïîñîáàìè. <itemizedlist> <listitem> <simpara> <link linkend="language.types.string.syntax.single">îäèíàðíûìè êàâ÷êàìè</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.string.syntax.double">äâîéíûìè êàâû÷êàìè</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.string.syntax.heredoc">heredoc-ñèíòàêñèñîì</link> </simpara> </listitem> </itemizedlist> </para> <sect3 id="language.types.string.syntax.single"> <title>Îäèíàðíûå êàâû÷êè</title> <para> Ïðîñòåéøèé ñïîñîá îïðåäåëèòü ñòðîêó - ýòî çàêëþ÷èòü åå â îäèíàðíûå êàâû÷êè (ñèìâîë <literal>'</literal>). </para> <para> ×òîáû èñïîëüçîâàòü îäèíàðíóþ êàâû÷êó âíóòðè ñòðîêè, êàê è âî ìíîãèõ äðóãèõ ÿçûêàõ, åå íåîáõîäèìî ïðåäâàðèòü ñèìâîëîì îáðàòíîé êîñîé ÷åðòû (<literal>\</literal>), ò. å. ìíåìîíèçèðîâàòü åå. Åñëè îáðàòíàÿ íàêëîííàÿ ÷åðòà äîëæíà èäòè ïåðåä îäèíàðíîé êàâû÷êîé ëèáî áûòü â êîíöå ñòðîêè, âàì íåîáõîäèìî ïðîäóáëèðîâàòü åå. Îáðàòèòå âíèìàíèå, ÷òî åñëè âû ïîïûòàåòåñü ìíåìîíèçèðîâàòü ëþáîé äðóãîé ñèìâîë, îáðàòíàÿ êîñàÿ ÷åðòà òàêæå áóäåò íàïå÷àòàíà! Òàê ÷òî, êàê ïðàâèëî, íåò íåîáõîäèìîñòè ìíåìîíèçèðîâàòü ñàìó îáðàòíóþ êîñóþ ÷åðòó. <note> <simpara>  PHP 3 â äàííîì ñëó÷àå áóäåò âûäàíî ñîîáùåíèå óðîâíÿ <literal>E_NOTICE</literal>. </simpara> </note> <note> <simpara>  îòëè÷èå îò äâóõ äðóãèõ ñèíòàêñèñîâ, ïåðåìåííûå, âñòðå÷àþùèåñÿ â ñòðîêàõ, çàêëþ÷åííûõ â îäèíàðíûå êàâû÷êè, <emphasis>íå</emphasis> îáðàáàòûâàþòñÿ. </simpara> </note> <informalexample> <programlisting role="php"> <![CDATA[ echo ''ýòî ïðîñòàÿ ñòðîêà'; echo 'Âû ìîæåòå âñòàâëÿòü â ñòðîêè ñèìâîë íîâîé ñòðîêè òàêèì îáðàçîì'; echo 'Îäíàæäû Àðíîëüä ñêàçàë: "I\'ll be back"'; // âûâîä: ... "I'll be back" echo 'Âû óâåðåíû, ÷òî õîòèòå óäàëèòü C:\\*.*?'; // âûâîä: ... óäàëèòü C:\*.*? echo 'Âû óâåðåíû, ÷òî õîòèòå óäàëèòü C:\*.*?'; // âûâîä: ... óäàëèòü C:\*.*? echo 'ß ïûòàþñü âñòàâèòü â ýòîé òî÷êå: \n ñèìâîë íîâîé ñòðîêè'; // âûâîä: ... â ýòîé òî÷êå: \n ñèìâîë íîâîé ñòðîêè ]]> </programlisting> </informalexample> </para> </sect3> <sect3 id="language.types.string.syntax.double"> <title>Äâîéíûå êàâû÷êè</title> <para> Åñëè ñòðîêà çàêëþ÷åíà â äâîéíûå êàâû÷êè ("), PHP ðàñïîçíàåò áîëüøåå êîëè÷åñòâî ìíåìîíèê ñïåöèàëüíûõ ñèìâîëîâ: </para> <table> <title>Ìíåìîíèêè ñèìâîëîâ</title> <tgroup cols="2"> <thead> <row> <entry>ïîñëåäîâàòåëüíîñòü</entry> <entry>çíà÷åíèå</entry> </row> </thead> <tbody> <row> <entry><literal>\n</literal></entry> <entry>íîâàÿ ñòðîêà (LF èëè 0x0A (10) â ASCII)</entry> </row> <row> <entry><literal>\r</literal></entry> <entry>âîçâðàò êàðåòêè (CR èëè 0x0D (13) â ASCII)</entry> </row> <row> <entry><literal>\t</literal></entry> <entry>ãîðèçîíòàëüíàÿ òàáóëÿöèÿ (HT èëè 0x09 (9) â ASCII)</entry> </row> <row> <entry><literal>\\</literal></entry> <entry>îáðàòíàÿ íàêëîííàÿ ÷åðòà</entry> </row> <row> <entry><literal>\$</literal></entry> <entry>çíàê äîëëàðà</entry> </row> <row> <entry><literal>\"</literal></entry> <entry>äâîéíàÿ êàâû÷êà</entry> </row> <row> <entry><literal>\[0-7]{1,3}</literal></entry> <entry> ïîñëåäîâàòåëüíîñòü ñèìâîëîâ, ñîîòâåòñâóþùàÿ ðåãóëÿðíîìó âûðàæåíèþ, ñèìâîë â âîñüìåðè÷íîé ñèñòåìå ñ÷èñëåíèÿ </entry> </row> <row> <entry><literal>\x[0-9A-Fa-f]{1,2}</literal></entry> <entry> ïîñëåäîâàòåëüíîñòü ñèìâîëîâ, ñîîòâåòñâóþùàÿ ðåãóëÿðíîìó âûðàæåíèþ, ñèìâîë â øåñòíàäöàòåðè÷íîé ñèñòåìå ñ÷èñëåíèÿ </entry> </row> </tbody> </tgroup> </table> <para> Ïîâòîðÿåì, åñëè âû çàõîòèòå ìíåìíîíèçèðîâàòü ëþáîé äðóãîé ñèìâîë, îáðàòíàÿ êîñàÿ ÷åðòà òàêæå áóäåò íàïå÷àòàíà! </para> <para> Íî ñàìûì âàæíûì ñâîéñòâîì ñòðîê â äâîéíûõ êàâû÷êàõ ÿâëÿåòñÿ îáðàáîòêà ïåðåìåííûõ. Ñìîòðèòå áîëåå ïîäðîáíî: <link linkend="language.types.string.parsing">îáðàáîòêà ñòðîê</link>. </para> </sect3> <sect3 id="language.types.string.syntax.heredoc"> <title>Heredoc</title> <simpara> Äðóãîé ñïîñîá îïðåäåëåíèÿ ñòðîê - ýòî èñïîëüçîâàíèå heredoc-ñèíòàêñèñà ("<<<"). One should provide an identifier after <literal><<<</literal>, then the string, and then the same identifier to close the quotation. </simpara> <simpara> The closing identifier <emphasis>must</emphasis> begin in the first column of the line. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore. </simpara> <warning> <simpara> It is very important to note that the line with the closing identifier contains no other characters, except <emphasis>possibly</emphasis> a semicolon (<literal>;</literal>). That means especially that the identifier <emphasis>may not be indented</emphasis>, and there may not be any spaces or tabs after or before the semicolon. </simpara> </warning> <para> Heredoc text behaves just like a double-quoted string, without the double-quotes. This means that you do not need to escape quotes in your here docs, but you can still use the escape codes listed above. Variables are expanded, but the same care must be taken when expressing complex variables inside a here doc as with strings. <example> <title>Heredoc string quoting example</title> <programlisting role="php"> <![CDATA[ <?php $str = <<<EOD Example of string spanning multiple lines using heredoc syntax. EOD; /* More complex example, with variables. */ class foo { var $foo; var $bar; function foo() { $this->foo = 'Foo'; $this->bar = array('Bar1', 'Bar2', 'Bar3'); } } $foo = new foo(); $name = 'MyName'; echo <<<EOT My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should print a capital 'A': \x41 EOT; ?> ]]> </programlisting> </example> </para> <note> <para> Heredoc support was added in PHP 4. </para> </note> </sect3> <sect3 id="language.types.string.parsing"> <title>Variable parsing</title> <simpara> When a string is specified in double quotes or with heredoc, variables are parsed within it. </simpara> <simpara> There are two types of syntax, a <link linkend="language.types.string.parsing.simple">simple</link> one and a <link linkend="language.types.string.parsing.complex">complex</link> one. The simple syntax is the most common and convenient, it provides a way to parse a variable, an array value, or an object property. </simpara> <simpara> The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression. </simpara> <sect4 id="language.types.string.parsing.simple"> <title>Simple syntax</title> <simpara> If a dollar sign (<literal>$</literal>) is encountered, the parser will greedily take as much tokens as possible to form a valid variable name. Enclose the variable name in curly braces if you want to explicitly specify the end of the name. </simpara> <informalexample> <programlisting role="php"> <![CDATA[ $beer = 'Heineken'; echo "$beer's taste is great"; // works, "'" is an invalid character for varnames echo "He drank some $beers"; // won't work, 's' is a valid character for varnames echo "He drank some ${beer}s"; // works ]]> </programlisting> </informalexample> <simpara> Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (<literal>]</literal>) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables. <!-- XXX isn't &true; :(, this would be the trick Also, the same trick with curly-braces works if you want to limit the greediness of parsers. --> </simpara> <informalexample> <programlisting role="php"> <![CDATA[ $fruits = array('strawberry' => 'red', 'banana' => 'yellow'); // note that this works differently outside string-quotes echo "A banana is $fruits[banana]."; echo "This square is $square->width meters broad."; // Won't work. For a solution, see the complex syntax. echo "This square is $square->width00 centimeters broad."; ]]> <!-- XXX this won't work: echo "This square is $square->{width}00 centimeters broad."; // XXX: php developers: it would be consequent to make this work. // XXX: like the $obj->{expr} syntax outside a string works, // XXX: analogously to the ${expr} syntax for variable var's. --> </programlisting> </informalexample> <simpara> For anything more complex, you should use the complex syntax. </simpara> </sect4> <sect4 id="language.types.string.parsing.complex"> <title>Complex (curly) syntax</title> <simpara> This isn't called complex because the syntax is complex, but because you can include complex expressions this way. </simpara> <simpara> In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can't escape '{', this syntax will only be recognised when the $ is immediately following the {. (Use "{\$" or "\{$" to get a literal "{$"). Some examples to make it clear: </simpara> <informalexample> <programlisting role="php"> <![CDATA[ $great = 'fantastic'; echo "This is { $great}"; // won't work, outputs: This is { fantastic} echo "This is {$great}"; // works, outputs: This is fantastic echo "This square is {$square->width}00 centimeters broad."; echo "This works: {$arr[4][3]}"; // This is wrong for the same reason // as $foo[bar] is wrong outside a string. echo "This is wrong: {$arr[foo][3]}"; echo "You should do it this way: {$arr['foo'][3]}"; echo "You can even write {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; ]]> <!-- maybe it's better to leave this out?? // this works, but i disencourage its use, since this is NOT // involving functions, rather than mere variables, arrays and objects. $beer = 'Heineken'; echo "I'd like to have another {${ strrev('reeb') }}, hips"; --> </programlisting> </informalexample> </sect4> </sect3> <sect3 id="language.types.string.substr"> <title>String access by character</title> <para> Characters within strings may be accessed by specifying the zero-based offset of the desired character after the string in curly braces. </para> <note> <simpara> For backwards compatibility, you can still use array-braces for the same purpose. However, this syntax is deprecated as of PHP 4. </simpara> </note> <para> <example> <title>Some string examples</title> <programlisting role="php"> <![CDATA[ <?php // Get the first character of a string $str = 'This is a test.'; $first = $str{0}; // Get the last character of a string. $str = 'This is still a test.'; $last = $str{strlen($str)-1}; ?> ]]> </programlisting> </example> </para> </sect3> </sect2><!-- end syntax --> <sect2 id="language.types.string.useful-funcs"> <title>Useful functions and operators</title> <para> Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see <link linkend="language.operators.string">String operators</link> for more information. </para> <para> There are a lot of useful functions for string modification. </para> <simpara> See the <link linkend="ref.strings">string functions section</link> for general functions, the regular expression functions for advanced find&replacing (in two tastes: <link linkend="ref.pcre">Perl</link> and <link linkend="ref.regex">POSIX extended</link>). </simpara> <simpara> There are also <link linkend="ref.url">functions for URL-strings</link>, and functions to encrypt/decrypt strings (<link linkend="ref.mcrypt">mcrypt</link> and <link linkend="ref.mhash">mhash</link>). </simpara> <simpara> Finally, if you still didn't find what you're looking for, see also the <link linkend="ref.ctype">character type functions</link>. </simpara> </sect2> <sect2 id="language.types.string.casting"> <title>Converting to string</title> <para> You can convert a value to a string using the <literal>(string)</literal> cast, or the <function>strval</function> function. String conversion is automatically done in the scope of an expression for you where a string is needed. This happens when you use the <function>echo</function> or <function>print</function> functions, or when you compare a variable value to a string. </para> <para> A boolean &true; value is converted to the string <literal>"1"</literal>, the &false; value is represented as <literal>""</literal> (empty string). This way you can convert back and forth between boolean and string values. </para> <para> An integer or a floating point number is converted to a string representing the number with its digits (includig the exponent part for floating point numbers). </para> <para> Arrays are always converted to the string <literal>"Array"</literal>, so you cannot dump out the contents of an array with <function>echo</function> or <function>print</function> to see what is inside them. See the information below for more tips. </para> <para> Objects are always converted to the string <literal>"Object"</literal>. If you would like to print out the member variable values of an object for debugging reasons, read the paragraphs below. If you would like to find out the class name of which an object is an instance of, use <function>get_class</function>. </para> <para> Resources are always converted to strings with the structure <literal>"Resource id #1"</literal> where <literal>1</literal> is the unique number of the resource assigned by PHP during runtime. If you would like to get the type of the resource, use <function>get_resource_type</function>. </para> <para> &null; is always converted to an empty string. </para> <para> As you can see above, printing out the arrays, objects or resources does not provide you any useful information about the values themselfs. Look at the functions <function>print_r</function> and <function>var_dump</function> for better ways to print out values for debugging. </para> <para> You can also convert PHP values to strings to store them permanently. This method is called serialization, and can be done with the function <function>serialize</function>. You can also serialize PHP values to XML structures, if you have <link linkend="ref.wddx">WDDX</link> support in your PHP setup. </para> </sect2> <sect2 id="language.types.string.conversion"> <title>String conversion to numbers</title> <simpara> When a string is evaluated as a numeric value, the resulting value and type are determined as follows. </simpara> <simpara> The string will evaluate as a <type>float</type> if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer. </simpara> <para> The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits. </para> <informalexample> <programlisting role="php"> <![CDATA[ $foo = 1 + "10.5"; // $foo is float (11.5) $foo = 1 + "-1.3e3"; // $foo is float (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) $foo = "10.0 pigs " + 1; // $foo is float (11) $foo = "10.0 pigs " + 1.0; // $foo is float (11) ]]> </programlisting> </informalexample> <simpara> For more information on this conversion, see the Unix manual page for strtod(3). </simpara> <para> If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on: <informalexample> <programlisting role="php"> <![CDATA[ echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n"; ]]> </programlisting> </informalexample> </para> <para> Do not expect to get the code of one character by converting it to integer (as you would do in C for example). Use the functions <function>ord</function> and <function>chr</function> to convert between charcodes and characters. </para> </sect2> </sect1><!-- end string --> <sect1 id="language.types.array"> <title>Arrays</title> <para> An array in PHP is actually an ordered map. A map is a type that maps <emphasis>values</emphasis> to <emphasis>keys</emphasis>. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP-array as a value, you can also quite easily simulate trees. </para> <para> Explanation of those structures is beyond the scope of this manual, but you'll find at least one example for each of those structures. For more information we refer you to external literature about this broad topic. </para> <sect2 id="language.types.array.syntax"> <title>Syntax</title> <sect3 id="language.types.array.syntax.array-func"> <title>Specifying with <function>array</function></title> <para> An <type>array</type> can be created by the <function>array</function> language-construct. It takes a certain number of comma-separated <literal><replaceable>key</replaceable> => <replaceable >value</replaceable></literal> pairs. </para> <para> <synopsis> array( <optional> <replaceable>key</replaceable> => </optional> <replaceable >value</replaceable> , ... ) // <replaceable>key</replaceable> is either <type>string</type > or nonnegative <type>integer</type> // <replaceable>value</replaceable> can be anything </synopsis> </para> <para> <informalexample> <programlisting role="php"> <![CDATA[ array("foo" => "bar", 12 => true); ]]> </programlisting> </informalexample> </para> <para> A <varname>key</varname> is either an <type>integer</type> or a <type>string</type>. If a key is the standard representation of an <type>integer</type>, it will be interpreted as such (i.e. <literal>"8"</literal> will be interpreted as <literal>8</literal>, while <literal>"08"</literal> will be interpreted as <literal>"08"</literal>). There are no different indexed and associative array types in PHP, there is only one array type, which can both contain integer and string indices. </para> <para> A value can be of any PHP type. <informalexample> <programlisting role="php"> <![CDATA[ array("somearray" => array(6 => 5, 13 => 9, "a" => 43)); ]]> </programlisting> </informalexample> </para> <para> If you omit a key, the maximum of the integer-indices is taken, and the new key will be that maximum + 1. As integers can be negative, this is also true for negative indices. Having e.g. the highest index being <literal>-6</literal> will result in being <literal>-5</literal> the new key. If no integer-indices exist yet, the key will be <literal>0</literal> (zero). If you specify a key that already has a value assigned to it, that value will be overwritten. <informalexample> <programlisting role="php"> <![CDATA[ // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ]]> </programlisting> </informalexample> </para> <para> Using &true; as a key will evalute to <type>integer</type> <literal>1</literal> as key. Using &false; as a key will evalute to <type>integer</type> <literal>0</literal> as key. Using <literal>NULL</literal> as a key will evaluate to an empty string. Using an emptry string as key will create (or overwrite) a key with an empty string and its value, it is not the same as using empty brackets. </para> <para> You cannot use arrays or objects as keys. Doing so will result in a warning: <literal>Illegal offset type</literal>. </para> </sect3> <sect3 id="language.types.array.syntax.modifying"> <title>Creating/modifying with square-bracket syntax</title> <para> You can also modify an existing array, by explicitly setting values in it. </para> <para> This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("<literal>[]</literal>") to the variable-name in that case. <synopsis> $arr[<replaceable>key</replaceable>] = <replaceable>value</replaceable>; $arr[] = <replaceable>value</replaceable>; // <replaceable>key</replaceable> is either <type>string</type > or nonnegative <type>integer</type> // <replaceable>value</replaceable> can be anything </synopsis> If <varname>$arr</varname> doesn't exist yet, it will be created. So this is also an alternative way to specify an array. To change a certain value, just assign a new value to an element specified with its key. If you want to remove a key/value pair, you need to <function>unset</function> it. <informalexample> <programlisting role="php"> <![CDATA[ $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ]]> </programlisting> </informalexample> </para> </sect3> </sect2><!-- end syntax --> <sect2 id="language.types.array.useful-funcs"> <title>Useful functions</title> <para> There are quite some useful function for working with arrays, see the <link linkend="ref.array">array functions</link> section. </para> <note> <para> The <function>unset</function> function allows unsetting keys of an array. Be aware that the array will NOT be reindexed. If you only use "usual integer indices" (starting from zero, increasing by one), you can achive the reindex effect by using <function>array_values</function>. <informalexample> <programlisting role="php"> <![CDATA[ $a = array(1 => 'one', 2 => 'two', 3 => 'three'); unset($a[2]); /* will produce an array that would have been defined as $a = array(1 => 'one', 3 => 'three'); and NOT $a = array(1 => 'one', 2 =>'three'); */ $b = array_values($a); // Now b is array(1 => 'one', 2 =>'three') ]]> </programlisting> </informalexample> </para> </note> <para> The <link linkend="control-structures.foreach">foreach</link> control structure exists specifically for arrays. It provides an easy way to traverse an array. </para> </sect2> <sect2 id="language.types.array.donts"> <title>Array do's and don'ts</title> <sect3 id="language.types.array.foo-bar"> <title>Why is <literal>$foo[bar]</literal> wrong?</title> <para> You should always use quotes around an associative array index. For example, use $foo['bar'] and not $foo[bar]. But why is $foo[bar] wrong? You might have seen the following syntax in old scripts: <informalexample> <programlisting role="php"> <![CDATA[ $foo[bar] = 'enemy'; echo $foo[bar]; // etc ]]> </programlisting> </informalexample> This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works, because the undefined constant gets converted to a string of the same name automatically for backward compatibility reasons. </para> <para> As stated in the <link linkend="language.types.array.syntax" >syntax</link> section, there must be an expression between the square brackets ('<literal>[</literal>' and '<literal>]</literal>'). That means that you can write things like this: <informalexample> <programlisting role="php"> <![CDATA[ echo $arr[foo(true)]; ]]> </programlisting> </informalexample> This is an example of using a function return value as the array index. PHP also knows about constants, as you may have seen the <literal>E_*</literal> ones before. <informalexample> <programlisting role="php"> <![CDATA[ $error_descriptions[E_ERROR] = "A fatal error has occured"; $error_descriptions[E_WARNING] = "PHP issued a warning"; $error_descriptions[E_NOTICE] = "This is just an informal notice"; ]]> </programlisting> </informalexample> Note that <literal>E_ERROR</literal> is also a valid identifier, just like <literal>bar</literal> in the first example. But the last example is in fact the same as writing: <informalexample> <programlisting role="php"> <![CDATA[ $error_descriptions[1] = "A fatal error has occured"; $error_descriptions[2] = "PHP issued a warning"; $error_descriptions[8] = "This is just an informal notice"; ]]> </programlisting> </informalexample> because <literal>E_ERROR</literal> equals <literal>1</literal>, etc. </para> <para> Then, how is it possible that <literal>$foo[bar]</literal> works? It works, because <literal>bar</literal> is due to its syntax expected to be a constant expression. However, in this case no constant with the name <literal>bar</literal> exists. PHP now assumes that you meant <literal>bar</literal> literally, as the string <literal>"bar"</literal>, but that you forgot to write the quotes. </para> <sect4> <title>So why is it bad then?</title> <para> At some point in the future, the PHP team might want to add another constant or keyword, or you may introduce another constant into your application, and then you get in trouble. For example, you already cannot use the words <literal>empty</literal> and <literal>default</literal> this way, since they are special <link linkend="reserved">reserved keywords</link>. </para> <note> <para> When you turn <link linkend="function.error-reporting" >error_reporting</link> to <literal>E_ALL</literal>, you will see that PHP generates notices whenever an <literal>index</literal> is used which is not defined. Consider this script: <informalexample> <programlisting role="php"> <![CDATA[ <?php // Turn on the display of all errors error_reporting(E_ALL); // Define the test array $abc = array("x" => "y"); // Access element with the *bad* method echo $abc[x]; ?> ]]> </programlisting> </informalexample> The output is: <informalexample> <programlisting> <![CDATA[ <br /> <b>Notice</b>: Use of undefined constant x - assumed 'x' in <b>/path/to/script.php</b> on line <b>10</b><br /> ]]> </programlisting> </informalexample> </para> </note> <note> <simpara> Inside a double-quoted <type>string</type>, another syntax is valid. See <link linkend="language.types.string.parsing" >variable parsing in strings</link> for more details. </simpara> </note> </sect4> </sect3> </sect2> <sect2 id="language.types.array.casting"> <title>Converting to array</title> <para> For any of the types: integer, float, string, boolean and resource, if you convert a value to an array, you get an array with one element (with index 0), which is the scalar value you started with. </para> <para> If you convert an object to an array, you get the properties (member variables) of that object as the array's elements. The keys are the member variable names. </para> <para> If you convert a &null; value to an array, you get an empty array. </para> </sect2> <sect2 id="language.types.array.examples"> <title>Examples</title> <para> The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays. </para> <para> <informalexample> <programlisting role="php"> <![CDATA[ // this $a = array( 'color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 'name' => 'apple', 4 // key will be 0 ); // is completely equivalent with $a['color'] = 'red'; $a['taste'] = 'sweet'; $a['shape'] = 'round'; $a['name'] = 'apple'; $a[] = 4; // key will be 0 $b[] = 'a'; $b[] = 'b'; $b[] = 'c'; // will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'), // or simply array('a', 'b', 'c') ]]> </programlisting> </informalexample> </para> <example> <title>Using array()</title> <programlisting role="php"> <![CDATA[ // Array as (property-)map $map = array( 'version' => 4, 'OS' => 'Linux', 'lang' => 'english', 'short_tags' => true ); // strictly numerical keys $array = array( 7, 8, 0, 156, -10 ); // this is the same as array(0 => 7, 1 => 8, ...) $switching = array( 10, // key = 0 5 => 6, 3 => 7, 'a' => 4, 11, // key = 6 (maximum of integer-indices was 5) '8' => 2, // key = 8 (integer!) '02' => 77, // key = '02' 0 => 12 // the value 10 will be overwritten by 12 ); // empty array $empty = array(); ]]> <!-- TODO example of - overwriting keys - using vars/functions as key/values - warning about references --> </programlisting> </example> <example id="language.types.array.examples.loop"> <title>Collection</title> <programlisting role="php"> <![CDATA[ $colors = array('red', 'blue', 'green', 'yellow'); foreach ($colors as $color) { echo "Do you like $color?\n"; } /* output: Do you like red? Do you like blue? Do you like green? Do you like yellow? */ ]]> </programlisting> </example> <para> Note that it is currently not possible to change the values of the array directly in such a loop. <!-- Should be made possible, if you write: foreach ( $colors as &$color ) See bug#3074 --> A workaround is the following: <example id="language.types.array.examples.changeloop"> <title>Collection</title> <programlisting role="php"> <![CDATA[ foreach ($colors as $key => $color) { // won't work: //$color = strtoupper($color); // works: $colors[$key] = strtoupper($color); } print_r($colors); /* output: Array ( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW ) */ ]]> </programlisting> </example> </para> <para> This example creates a one-based array. <example> <title>One-based index</title> <programlisting role="php"> <![CDATA[ $firstquarter = array(1 => 'January', 'February', 'March'); print_r($firstquarter); /* output: Array ( [1] => 'January' [2] => 'February' [3] => 'March' ) */ ]]> </programlisting> </example> </para> <example> <title>Filling an array</title> <programlisting role="php"> <![CDATA[ // fill an array with all items from a directory $handle = opendir('.'); while ($file = readdir($handle)) { $files[] = $file; } closedir($handle); ]]> </programlisting> </example> <para> Arrays are ordered. You can also change the order using various sorting-functions. See the <link linkend="ref.array">array functions</link> section for more information. You can count the number of items in an array using the <function>count</function> function. </para> <example> <title>Sorting array</title> <programlisting role="php"> <![CDATA[ sort($files); print_r($files); ]]> </programlisting> </example> <para> Because the value of an array can be everything, it can also be another array. This way you can make recursive and multi-dimensional arrays. </para> <example> <title>Recursive and multi-dimensional arrays</title> <programlisting role="php"> <![CDATA[ $fruits = array ( "fruits" => array ( "a" => "orange", "b" => "banana", "c" => "apple" ), "numbers" => array ( 1, 2, 3, 4, 5, 6, ), "holes" => array ( "first", 5 => "second", "third" ) ); // Some examples to address values in the array above echo $fruits["holes"][5]; // prints "second" echo $fruits["fruits"]["a"]; // prints "orange" unset($fruits["holes"][0]); // remove "first" // Create a new multi-dimensional array $juices["apple"]["green"] = "good"; ]]> </programlisting> </example> <para> You should be aware, that array assignment always involves value copying. You need to use the reference operator to copy an array by reference. <informalexample> <programlisting role="php"> <![CDATA[ $arr1 = array(2, 3); $arr2 = $arr1; $arr2[] = 4; // $arr2 is changed, // $arr1 is still array(2,3) $arr3 = &$arr1; $arr3[] = 4; // now $arr1 and $arr3 are the same ]]> </programlisting> </informalexample> </para> </sect2> </sect1> <sect1 id="language.types.object"> <title>Objects</title> <sect2 id="language.types.object.init"> <title>Object Initialization</title> <para> To initialize an object, you use the <literal>new</literal> statement to instantiate the object to a variable. <informalexample> <programlisting role="php"> <![CDATA[ <?php class foo { function do_foo() { echo "Doing foo."; } } $bar = new foo; $bar->do_foo(); ?> ]]> </programlisting> </informalexample> </para> <simpara> For a full discussion, please read the section <link linkend="language.oop">Classes and Objects</link>. </simpara> </sect2> <sect2 id="language.types.object.casting"> <title>Converting to object</title> <para> If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instace of the <literal>stdClass</literal> built in class is created. If the value was null, the new instance will be empty. For any other value, a member variable named <literal>scalar</literal> will contain the value. <informalexample> <programlisting role="php"> $obj = (object) 'ciao'; echo $obj->scalar; // outputs 'ciao' </programlisting> </informalexample> </para> </sect2> </sect1> <sect1 id="language.types.resource"> <title>Resource</title> <para> A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the <link linkend="resource">appendix</link> for a listing of all these functions and the corresponding resource types. </para> <note> <simpara> The resource type was introduced in PHP 4 </simpara> </note> <sect2 id="language.types.resource.casting"> <title>Converting to resource</title> <para> As resource types hold special handlers to opened files, database connections, image canvas areas and the like, you cannot convert any value to a resource. </para> </sect2> <sect2 id="language.types.resource.self-destruct"> <title>Freeing resources</title> <para> Due to the reference-counting system introduced with PHP4's Zend-engine, it is automatically detected when a resource is no longer referred to (just like Java). When this is the case, all resources that were in use for this resource are made free by the garbage collector. For this reason, it is rarely ever necessary to free the memory manually by using some free_result function. <note> <simpara> Persistent database links are special, they are <emphasis>not</emphasis> destroyed by the garbage collector. See also the section about <link linkend="features.persistent-connections">persistent connections</link>. </simpara> </note> </para> </sect2> </sect1> <sect1 id="language.types.null"> <title>NULL</title> <para> The special &null; value represents that a variable has no value. &null; is the only possible value of type <type>NULL</type>. </para> <note> <simpara> The null type was introduced in PHP 4 </simpara> </note> <para> A variable is considered to be &null; if <itemizedlist> <listitem> <para> it has been assigned the constant &null;. </para> </listitem> <listitem> <para> it has not been set to any value yet. </para> </listitem> <listitem> <para> it has been <function>unset</function>. </para> </listitem> </itemizedlist> </para> <sect2 id="language.types.null.syntax"> <title>Syntax</title> <para> There is only one value of type &null;, and that is the case-insensitive keyword &null;. <informalexample> <programlisting role="php"> $var = NULL; </programlisting> </informalexample> </para> <para> See also <function>is_null</function> and <function>unset</function>. </para> </sect2> </sect1> <sect1 id="language.pseudo-types"> <title>Pseudo-types used in this documentation</title> <sect2 id="language.types.mixed"> <title>mixed</title> <para> <literal>mixed</literal> indicates that a parameter may accept multiple (but not necesseraly all) types. </para> <para> <function>gettype</function> for example will accept all PHP types, while <function>str_replace</function> will accept strings and arrays. </para> </sect2> <sect2 id="language.types.number"> <title>number</title> <para> <literal>number</literal> indicates that a parameter can be either <type>integer</type> or <type>float</type>. </para> </sect2> <sect2 id="language.types.callback"> <title>callback</title> <para> Some functions like <function>call_user_function</function> or <function>usort</function> accept user defined callback functions as a parameter. Callback functions can not only be simple functions but also object methods including static class methods. </para> <para> A PHP function is simply passed by its name as a string. You can pass any builtin or user defined function with the exception of <function>array</function>, <function>echo</function>, <function>empty</function>, <function>eval</function>, <function>exit</function>, <function>isset</function>, <function>list</function>, <function>print</function> and <function>unset</function>. </para> <para> A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1. </para> <para> Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object as the element with index 0. </para> <para> <example> <title> Callback function examples </title> <programlisting role="php"> <![CDATA[ <?php // simple callback example function foobar() { echo "hello world!"; } call_user_function("foobar"); // method callback examples class foo { function bar() { echo "hello world!"; } } $foo = new foo; call_user_function(array($foo, "bar")); // object method call call_user_function(array("foo", "bar")); // static class method call ?> ]]> </programlisting> </example> </para> </sect2> </sect1> <sect1 id="language.types.type-juggling"> <title>Type Juggling</title> <simpara> PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable <parameter>$var</parameter>, <parameter>$var</parameter> becomes a string. If you then assign an integer value to <parameter>$var</parameter>, it becomes an integer. </simpara> <para> An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated. <informalexample> <programlisting role="php"> $foo = "0"; // $foo is string (ASCII 48) <!-- bad example, no real operator (must be used with variable, modifies it too) $foo++; // $foo is the string "1" (ASCII 49) --> $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) <!-- TODO: explain ++/- - behaviour with strings examples: ++'001' = '002' ++'abc' = 'abd' ++'xyz' = 'xza' ++'9.9' = '9.0' ++'-3' = '-4' - -'9' = 8 (integer!) - -'5.5' = '5.5' - -'-9' = -10 (integer) - -'09' = 8 (integer) - -'abc' = 'abc' --> </programlisting> </informalexample> </para> <simpara> If the last two examples above seem odd, see <link linkend="language.types.string.conversion">String conversion to numbers</link>. </simpara> <simpara> If you wish to force a variable to be evaluated as a certain type, see the section on <link linkend="language.types.typecasting">Type casting</link>. If you wish to change the type of a variable, see <function>settype</function>. </simpara> <para> If you would like to test any of the examples in this section, you can use the <function>var_dump</function> function. </para> <note> <para> The behaviour of an automatic conversion to array is currently undefined. </para> <para> <informalexample> <programlisting role="php"> $a = "1"; // $a is a string $a[0] = "f"; // What about string offsets? What happens? </programlisting> </informalexample> </para> <para> Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a? </para> <para> The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes "f", the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above: <informalexample> <programlisting role="php"> $a = "abc"; // $a is a string $a{1} = "f"; // $a is now "afc" </programlisting> </informalexample> See the section titled <link linkend="language.types.string.substr">String access by character</link> for more informaton. </para> </note> <sect2 id="language.types.typecasting"> <title>Type Casting</title> <para> Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast. <informalexample> <programlisting role="php"> $foo = 10; // $foo is an integer $bar = (boolean) $foo; // $bar is a boolean </programlisting> </informalexample> </para> <para> The casts allowed are: <itemizedlist> <listitem> <simpara>(int), (integer) - cast to integer</simpara> </listitem> <listitem> <simpara>(bool), (boolean) - cast to boolean</simpara> </listitem> <listitem> <simpara>(float), (double), (real) - cast to float</simpara> </listitem> <listitem> <simpara>(string) - cast to string</simpara> </listitem> <listitem> <simpara>(array) - cast to array</simpara> </listitem> <listitem> <simpara>(object) - cast to object</simpara> </listitem> </itemizedlist> </para> <para> Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent: <informalexample> <programlisting role="php"> $foo = (int) $bar; $foo = ( int ) $bar; </programlisting> </informalexample> </para> <note> <para> Instead of casting a variable to string, you can also enclose the variable in double quotes. <informalexample> <programlisting role="php"> $foo = 10; // $foo is an integer $str = "$foo"; // $str is a string $fst = (string) $foo; // $fst is also a string // This prints out that "they are the same" if ($fst === $str) { echo "they are the same"; } </programlisting> </informalexample> </para> </note> <para> It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections: <itemizedlist> <listitem> <simpara><link linkend="language.types.boolean.casting">Converting to boolean</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.integer.casting">Converting to integer</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.float.casting">Converting to float</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.string.casting">Converting to string</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.array.casting">Converting to array</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.object.casting">Converting to object</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.resource.casting">Converting to resource</link></simpara> </listitem> <!-- don't exist yet <listitem> <simpara><link linkend="language.types.null.casting">Converting to &null;</link></simpara> </listitem> --> </itemizedlist> </para> </sect2> </sect1> </chapter> <!-- 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:"../../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 -->
Index: phpdoc-ru/language/types.xml +++ phpdoc-ru/language/types.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- EN-Revision: 1.98 Maintainer: Kai Status: ready --> <!-- $Revision: 1.1 $ --> <chapter id="language.types"> <title>Òèïû</title> <!-- Çàìå÷àíèå: Ïîñëåäíåå èçìåíåíèå çàìåòêè: 2003-09-01 resource ïåðåâåë êàê èñòî÷íèê control structure = óïðàâëÿþùàÿ êîíñòðóêöèÿ language.types.string.conversion = Êîíâåðòàöèÿ ñòðîê â ÷èñëà Arbitrary Precision Mathematics Functions=ìàòåìàòè÷åñêèå ôóêöèè ïðîèçâîëüíîé òî÷íîñòè String conversion to numbers = Êîíâåðòàöèÿ ñòðîê â ÷èñëà language.types.integer.casting = è äðóãèå ññûëêè - óòî÷íèòü heredoc-ñèíòàêñèñ - êàê ïåðåâåñòè? Escaped characters --> <sect1 id="language.types.intro"> <title>Ââåäåíèå</title> <simpara> PHP ïîääåðæèâàåò âîñåìü ïðîñòûõ òèïîâ. </simpara> <para> ×åòûðå ñêàëÿðíûõ òèïà: <itemizedlist> <listitem> <simpara> <link linkend="language.types.boolean">áóëåâ</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.integer">öåëîå</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.float">÷èñëî ñ ïëàâàþùåé òî÷êîé</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.string">ñòðîêà</link> </simpara> </listitem> </itemizedlist> Äâà ñìåøàííûõ òèïà: <itemizedlist> <listitem> <simpara> <link linkend="language.types.array">ìàññèâ</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.object">îáúåêò</link> </simpara> </listitem> </itemizedlist> È, íàêîíåö, äâà ñïåöèàëüíûõ òèïà: <itemizedlist> <listitem> <simpara> <link linkend="language.types.resource">èñòî÷íèê</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.null">NULL</link> </simpara> </listitem> </itemizedlist>  ýòîé äîêóìåíòàöèè òàêæå ïðåäñòàâëåíî íåñêîëüêî <link linkend="language.pseudo-types">ïñåâäî-òèïîâ</link> äëÿ óäîáñòâà ïîíèìàíèÿ: <itemizedlist> <listitem> <simpara> <link linkend="language.types.mixed">ñìåøàííûé</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.number">÷èñëî</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.mixed">îáðàòíûé âûçîâ (callback)</link> </simpara> </listitem> </itemizedlist> Âû òàêæå ìîæåòå íàéòè íåñêîëüêî óïîìèíàíèé òèïà äâîéíîé òî÷íîñòè. Ðàññìàòðèâàéòå åãî êàê ÷èñëî ñ ïëàâàþùåé òî÷êîé, äâà èìåíè ñóùåñòâóþò òîëüêî ïî èñòîðè÷åñêèì ïðè÷èíàì. </para> <simpara> Êàê ïðàâèëî, ïðîãðàììèñò íå óñòàíàâëèâàåò òèï ïåðåìåííîé; ïðåäïî÷òèòåëüíåå, ÷òîáû ýòî äåëàë PHP âî âðåìÿ âûïîëíåíèÿ ïðîãðàììû â çàâèñèìîñòè îò êîíòåêñòà, â êîòîðîì èñïîëüçóåòñÿ ïåðåìåííàÿ. </simpara> <note> <simpara> Åñëè âû æåëàåòå ïðîâåðèòü òèï è çíà÷åíèå îïðåäåëåííîãî <link linkend="language.expressions">âûðàæåíèÿ</link>, èñïîëüçóéòå <function>var_dump</function>. </simpara> <para> Åñëè æå âàì äëÿ îòëàäêè íåîáõîäèìî ïðîñòî óäîáî÷èòàåìîå ïðåäñòàâëåíèå òèïà, èñïîëüçóéòå <function>gettype</function>. ×òîáû ïðîâåðèòü íà îïðåäåëåííûé òèï, <emphasis>íå</emphasis> èñïîëüçóéòå <function>gettype</function>, ïðèìåíÿéòå äëÿ ýòîãî <literal>is_<replaceable>type</replaceable></literal> ôóíêöèè. Âîò íåñêîëüêî ïðèìåðîâ: <informalexample> <programlisting role="php"> <![CDATA[ $bool = TRUE; // ëîãè÷åñêèé $str = "foo"; // ñòðîêîâûé $int = 12; // öåëî÷èñëåííûé echo gettype($bool); // âûâîäèò "boolean" echo gettype($str); // âûâîäèò "string" // Åñëè ýòî öåëîå, óâåëè÷èòü íà ÷åòûðå if (is_int($int)) { $int += 4; } // Åñëè $bool - ýòî ñòðîêà, âûâåñòè åå // (íè÷åãî íå âûâîäèò) if (is_string($bool)) { echo "Ñòðîêà: $bool"; } ]]> </programlisting> </informalexample> </para> </note> <simpara> Åñëè âû õîòèòå ïðèíóäèòåëüíî èçìåíèòü òèï ïåðåìåííîé, âû ìîæåòå ëèáî <link linkend="language.types.typecasting">ïðèâåñòè</link> ïåðåìåííóþ, ëèáî èñïîëüçîâàòü ôóíêöèþ <function>settype</function>. </simpara> <simpara> Îáðàòèòå âíèìàíèå, ÷òî ïåðåìåííàÿ, â çàâèñèìîñòè îò åå òèïà â äàííûé ìîìåíò, â îïðåäåëåííûõ ñèòóàöèÿõ ìîæåò èìåòü ðàçíûå çíà÷åíèÿ. Áîëåå ïîäðîáíóþ èíôîðìàöèþ ñìîòðèòå â ðàçäåëå <link linkend="language.types.type-juggling">Ìàíèïóëÿöèè ñ òèïàìè</link>. </simpara> </sect1> <sect1 id="language.types.boolean"> <title>Áóëåâ</title> <simpara> Ýòî ïðîñòåéøèé òèï. Îí âûðàæàåò èñòèííîñòü çíà÷åíèÿ - ýòî ìîæåò áûòü ëèáî &true;, ëèáî &false;. </simpara> <note> <simpara> Áóëåâ òèï áûë ââåäåí â PHP 4. </simpara> </note> <sect2 id="language.types.boolean.syntax"> <title>Ñèíòàêñèñ</title> <para> ×òîáû îïðåäåëèòü áóëåâ òèï, èñïîëüçóéòå êëþ÷åâîå ñëîâî &true; èëè &false;. Îáà ðåãèñòðî-íåçàâèñèìû. <informalexample> <programlisting role="php"> <![CDATA[ $foo = True; // îïðåäåëèòü $foo êàê TRUE ]]> </programlisting> </informalexample> </para> <para> Îáû÷íî âû èñïîëüçóåòå íåêèé <link linkend="language.operators">îïåðàòîð</link>, êîòîðûé âîçâðàùàåò ëîãè÷åñêîå âûðàæåíèå, à çàòåì ïðåäàåò åãî <link linkend="control-structures">óïðàâëÿþùåé êîíñòðóêöèè</link>. <informalexample> <programlisting role="php"> <![CDATA[ // == ýòî îïåðàòîð, êîòîðûé ïðîâåðÿåò // ýêâèâàëåíòíîñòü è âîçâðàùàåò áóëåâî çíà÷åíèå if ($action == "ïîêàçàòü_âåðñèþ") { echo "Âåðñèÿ 1.23"; } // ýòî íå îáÿçàòåëüíî... if ($show_separators == TRUE) { echo "<hr>\n"; } // ...ïîòîìó ÷òî âû ìîæåòå ïðîñòî íàïèñàòü if ($show_separators) { echo "<hr>\n"; } ]]> </programlisting> </informalexample> </para> </sect2> <sect2 id="language.types.boolean.casting"> <title>Êîíâåðòàöèÿ â áóëåâ òèï</title> <simpara> Äëÿ íåñîìíåííîé êîíâåðòàöèè çíà÷åíèÿ â áóëåâ òèï èñïîëüçóéòå ïðèâèäåíèå òèïà <literal>(bool)</literal> èëè <literal>(boolean)</literal>. Îäíàêî â áîëüøèíñòâå ñëó÷àåâ âàì íåò íåîáõîäèìîñòè èñïîëüçîâàòü ïðèâèäåíèå òèïà, ïîñêîëüêó çíà÷åíèå áóäåò àâòîìàòè÷åñêè êîíâåðòèðîâàíî, åñëè îïåðàòîð, ôóíêöèÿ èëè óïðàâëÿþùàÿ êîíñòðóêöèÿ òðåáóåò áóëåâ àðãóìåíò. </simpara> <simpara> Ñìîòðèòå òàêæå <link linkend="language.types.type-juggling">Ìàíèïóëÿöèè ñ òèïàìè</link>. </simpara> <para> Ïðè êîíâåðòàöèè â ëîãè÷åñêèé òèï, ñëåäóþùèå çíà÷åíèÿ ðàññìàòðèâàþòñÿ êàê &false;: <itemizedlist> <listitem> <simpara>Ñàì <link linkend="language.types.boolean">áóëåâ</link> &false;</simpara> </listitem> <listitem> <simpara><link linkend="language.types.integer">öåëîå</link > 0 (íîëü) </simpara> </listitem> <listitem> <simpara><link linkend="language.types.float">÷èñëî ñ ïëàâàþùåé òî÷êîé</link> 0.0 (íîëü) </simpara> </listitem> <listitem> <simpara>ïóñòàÿ <link linkend="language.types.string" >ñòðîêà</link> è <link linkend="language.types.string" >ñòðîêà</link> "0"</simpara> </listitem> <listitem> <simpara><link linkend="language.types.array">ìàññèâ</link> ñ íóëåâûìè ýëåìåíòàìè</simpara> </listitem> <listitem> <simpara><link linkend="language.types.object">îáúåêò</link> ñ íóëåâûìè ïåðåìåííûìè-÷ëåíàìè</simpara> </listitem> <listitem> <simpara>ñïåöèàëüíûé òèï <link linkend="language.types.null" >NULL</link> (âêëþ÷àÿ íåóñòàíîâëåííûå ïåðåìåííûå) </simpara> </listitem> </itemizedlist> Âñå îñòàëüíûå çíà÷åíèÿ ðàññìàòðèâàþòñÿ êàê &true; (âêëþ÷àÿ ëþáîé <link linkend="language.types.resource">èñòî÷íèê</link>). <warning> <simpara> <literal>-1</literal> ñ÷èòàåòñÿ &true;, êàê è ëþáîå íåíóëåâîå (îòðèöàòåëüíîå èëè ïîëîæèòåëüíîå) ÷èñëî! </simpara> </warning> <informalexample> <programlisting role="php"> <![CDATA[ echo gettype((bool) ""); // bool(false) echo gettype((bool) 1); // bool(true) echo gettype((bool) -2); // bool(true) echo gettype((bool) "foo"); // bool(true) echo gettype((bool) 2.3e5); // bool(true) echo gettype((bool) array(12)); // bool(true) echo gettype((bool) array()); // bool(false) ]]> </programlisting> </informalexample> </para> </sect2> </sect1> <sect1 id="language.types.integer"> <title>Öåëûå</title> <simpara> Öåëîå ýòî ÷èñëî èç ìíîæåñòâà Z = {..., -2, -1, 0, 1, 2, ...}. </simpara> <para> Ñìîòðèòå òàêæå: <link linkend="ref.gmp">Öåëûå ïðîèçâîëüíîé äëèíû</link> è <link linkend="language.types.float">×èñëà ñ ïëàâàþùåé òî÷êîé</link> </para> <sect2 id="language.types.integer.syntax"> <title>Ñèíòàêñèñ</title> <simpara> Öåëûå ìîãóò áûòü óêàçàíû â äåñÿòè÷íîé, øåñòíàäöàòåðè÷íîé èëè âîñüìåðè÷íîé ñèñòåìå ñ÷èñëåíèÿ, ïî æåëàíèþ ñ ïðåäøåñòâóþùèì çíàêîì (- èëè +). </simpara> <para> Åñëè âû èñïîëüçóåòå âîñüìåðè÷íóþ ñèñòåìó ñ÷èñëåíèÿ, âû äîëæíû ïðåäâàðèòü ÷èñëî <literal>0</literal> (íóëåì), äëÿ èñïîëüçîâàíèÿ øåñòíàäöàòåðè÷íîé ñèñòåìû íóæíî ïîñòàâèòü ïåðåä ÷èñëîì <literal>0x</literal>. <example> <title>Öåëûå</title> <programlisting role="php"> <![CDATA[ $a = 1234; # äåñÿòè÷íîå ÷èñëî $a = -123; # îòðèöàòåëüíîå ÷èñëî $a = 0123; # âîñüìåðè÷íîå ÷èñëî (ýêâèâàëåíòíî 83 â äåñÿòè÷íîé ñèñòåìå) $a = 0x1A; # øåñòíàäöàòåðè÷íîå ÷èñëî (ýêâèâàëåíòíî 26 â äåñÿòè÷íîé ñèñòåìå) ]]> </programlisting> </example> Ôîðìàëüíî âîçìîæíàÿ ñòðóêòóðà öåëûõ òàêîâà: <informalexample> <programlisting> <![CDATA[ äåñÿòè÷íûå : [1-9][0-9]* | 0 øåñòíàäöàòåðè÷íûå : 0[xX][0-9a-fA-F]+ âîñüìåðè÷íûå : 0[0-7]+ öåëûå : [+-]?äåñÿòè÷íûå | [+-]?øåñòíàäöàòåðè÷íûå | [+-]?âîñüìåðè÷íûå ]]> </programlisting> </informalexample> Ðàçìåð öåëîãî çàâèñèò îò ïëàòôîðìû, õîòÿ, êàê ïðàâèëî, ìàêñèìàëüíîå çíà÷åíèå îêîëî äâóõ ìèëëèàðäîâ (ýòî 32-áèòíîå çíàêîâîå). PHP íå ïîääåðæèâàåò áåççíàêîâûå öåëûå. </para> </sect2> <sect2 id="language.types.integer.overflow"> <title>Ïðåâûøåíèå ðàçìåðà öåëîãî</title> <para> Åñëè âû îïðåäåëèòå ÷èñëî, ïðåâûøàþùåå ïðåäåëû öåëîãî òèïà, îíî áóäåò èíòåðïðåòèðîâàíî êàê ÷èñëî ñ ïëàâàþùåé òî÷êîé. Òàêæå, åñëè âû èñïîëüçóåòå îïåðàòîð, ðåçóëüòàòîì ðàáîòû êîòîðîãî áóäåò ÷èñëî, ïðåâûøàþùåå ïðåäåëû öåëîãî, âìåñòî íåãî áóäåò âîçâðàùåíî ÷èñëî ñ ïëàâàþùåé òî÷êîé. <informalexample> <programlisting role="php"> <![CDATA[ $large_number = 2147483647; var_dump($large_number); // âûâîä: int(2147483647) $large_number = 2147483648; var_dump($large_number); // âûâîä: float(2147483648) // ýòî ñïðàâåäëèâî è äëÿ øåñòíàäöàòåðè÷íûõ öåëûõ: var_dump( 0x80000000 ); // âûâîä: float(2147483648) $million = 1000000; $large_number = 50000 * $million; var_dump($large_number); // âûâîä: float(50000000000) ]]> </programlisting> </informalexample> <warning> <simpara> Ê ñîæàëåíèþ, â PHP áûëà îøèáêà, òàê ÷òî ýòî íå âñåãäà âåðíî ðàáîòàåò, êîãäà èñïîëüçóþòñÿ îòðèöàòåëüíûå ÷èñëà. Íàïðèìåð: êîãäà âû óìíîæàåòå <literal>-50000 * $million</literal>, ðåçóëüòàòîì áóäåò <literal>-429496728</literal>. Îäíàêî, åñëè îáà îïåðàíäà ïîëîæèòåëüíû, ïðîáëåì íå âîçíèêàåò. </simpara> <simpara> Ýòà îøèáêà óñòðàíåíà â PHP 4.1.0. </simpara> </warning> </para> <para> â PHP íå ñóùåñòâóåò îïåðàòîðà äåëåíèÿ öåëûõ. Ðåçóëüòàòîì <literal>1/2</literal> áóäåò ÷èñëî ñ ïëàâàþùåé òî÷êîé <literal>0.5</literal>. Âû ìîæåòå ïðèâåñòè çíà÷åíèå ê öåëîìó, ÷òî âñåãäà îêðóãëÿåò åãî â ìåíüøóþ ñòîðîíó, ëèáî èñïîëüçîâàòü ôóíêöèþ <function>round</function>. <informalexample> <programlisting role="php"> <![CDATA[ var_dump(25/7); // float(3.5714285714286) var_dump((int) (25/7)); // int(3) var_dump(round(25/7)); // float(4) ]]> </programlisting> </informalexample> </para> </sect2> <sect2 id="language.types.integer.casting"> <title>Êîíâåðòàöèÿ â öåëîå</title> <simpara> Äëÿ íåñîìíåííîé êîíâåðòàöèè çíà÷åíèÿ â öåëîå èñïîëüçóéòå ïðèâèäåíèå òèïà <literal>(int)</literal> èëè <literal>(integer)</literal>. Îäíàêî â áîëüøèíñòâå ñëó÷àåâ âàì íåò íåîáõîäèìîñòè èñïîëüçîâàòü ïðèâèäåíèå òèïà, ïîñêîëüêó çíà÷åíèå áóäåò àâòîìàòè÷åñêè êîíâåðòèðîâàíî, åñëè îïåðàòîð, ôóíêöèÿ èëè óïðàâëÿþùàÿ êîíñòðóêöèÿ òðåáóåò öåëûé àðãóìåíò. Âû òàêæå ìîæåòå êîíâåðòèðîâàòü çíà÷åíèå â öåëîå ïðè ïîìîùè ôóíêöèè <function>intval</function>. </simpara> <simpara> Ñìîòðèòå òàêæå <link linkend="language.types.type-juggling">Ìàíèïóëÿöèè ñ òèïàìè</link>. </simpara> <sect3 id="language.types.integer.casting.from-boolean"> <title>Èç <link linkend="language.types.boolean" >áóëåâà</link> òèïà</title> <simpara> &false; êîíâåðòèðóåòñÿ â <literal>0</literal> (íîëü), à &true; - â <literal>1</literal> (åäèíèöó). </simpara> </sect3> <sect3 id="language.types.integer.casting.from-float"> <title>Èç <link linkend="language.types.float">÷èñåë ñ ïëàâàþùåé òî÷êîé</link></title> <simpara> Ïðè êîíâåðòàöèè èç ÷èñëà ñ ïëàâþùåé òî÷êîé â öåëîå, ÷èñëî áóäåò îêðóãëåíî <emphasis>â ñòîðîíó íóëÿ</emphasis>. </simpara> <para> Åñëè ÷èñëî ñ ïëàâàþùåé òî÷êîé ïðåâûøàåò ïðåäåëû öåëîãî (êàê ïðàâèëî, ýòî <literal>+/- 2.15e+9 = 2^31</literal>), ðåçóëüòàò áóäåò íåîïðåäåë¸ííûì, òàê êàê öåëîå íå èìååò äîñòàòî÷íîé òî÷íîñòè, ÷òîáû âåðíóòü âåðíûé ðåçóëüòàò.  ýòîì ñëó÷àå íå áóäåò âûâåäåíî íè ïðåäóïðåæäåíèÿ, íè äàæå çàìå÷àíèÿ! </para> <warning><para> Íèêîãäà íå ïðèâîäèòå íåèçâåñòíóþ äðîáü ê öåëîìó, òàê êàê ýòî ìîæåò èíîãäà äàòü íåîæèäàííûå ðåçóëüòàòû. <informalexample> <programlisting role="php"> <![CDATA[ echo (int) ( (0.1+0.7) * 10 ); // âûâîäèò 7! ]]> </programlisting> </informalexample> Ñìîòðèòå áîëåå ïîäðîáíî: <link linkend="warn.float-precision">ïðåäóïðåæäåíèå î òî÷íîñòè ÷èñëåë ñ ïëàâàþùåé òî÷êîé</link>. </para></warning> </sect3> <sect3 id="language.types.integer.casting.from-string"> <title>Èç ñòðîê</title> <simpara> Ñìîòðèòå <link linkend="language.types.string.conversion">Êîíâåðòàöèÿ ñòðîê â ÷èñëà</link> </simpara> </sect3> <sect3 id="language.types.integer.casting.from-other"> <title>Èç äðóãèõ òèïîâ</title> <para> <caution> <simpara> Äëÿ äðóãèõ òèïîâ ïîâåäåíèå êîíâåðòàöèè â öåëîå íå îïðåäåëåíî.  íàñòîÿùåå âðåìÿ ïîâåäåíèå òàêîå æå, êàê åñëè áû çíà÷åíèå ñïåðâà áûëî <link linkend="language.types.boolean.casting" >êîíâåðòèðîâàíî â áóëåâ òèï</link>. Îäíàêî <emphasis>íå</emphasis> ïîëàãàéòåñü íà ýòî ïîâåäåíèå, òàê êàê îí ìîæåò èçìåíèòüñÿ áåç ïðåäóïðåæäåíèÿ. </simpara> </caution> </para> </sect3> </sect2> </sect1> <sect1 id="language.types.float"> <title>×èñëà ñ ïëàâþùåé òî÷êîé</title> <para> ×èñëà ñ ïëàâþùåé òî÷êîé (îíè æå ÷èñëà äâîéíîé òî÷íîñòè èëè äåéñòâèòåëüíûå ÷èñëà) ìîãóò áûòü îïðåäåëåíû ïðè ïîìîùè ëþáîãî èç ñëåäóþùèõ ñèíòàêñèñîâ: <informalexample> <programlisting role="php"> $a = 1.234; $a = 1.2e3; $a = 7E-10; </programlisting> </informalexample> Ôîðìàëüíî: <informalexample> <programlisting role="php"> LNUM [0-9]+ DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*) EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM}) </programlisting> </informalexample> Ðàçìåð öåëîãî çàâèñèò îò ïëàòôîðìû, õîòÿ ìàêñèìóì, êàê ïðàâèëî, ~1.8e308 ñ òî÷íîñòüþ îêîëî 14 äåñÿòè÷íûõ öèôð (ýòî 64-áèòíûé IEEE-ôîðìàò). </para> <warning id="warn.float-precision"> <title>Òî÷íîñòü ÷èñëà ñ ïëàâàþùåé òî÷êîé</title> <para> Äîâîëüíî ÷àñòî ïðîñòûå äåñÿòè÷íûå äðîáè âðîäå <literal>0.1</literal> èëè <literal>0.7</literal> íå ìîãóò áûòü êîíâåðòèðîâàíû â ñâîè âíóòðåííèå äâîè÷íûå àíàëîãè áåç íåáîëüøîé ïîòåðè òî÷íîñòè. Ýòî ìîæåò ïðèâåñòè ê íåîæèäàííûì ðåçóëüòàòàì: íàïðèìåð, <literal>floor((0.1+0.7)*10)</literal> ñêîðåå âñåãî âîçâðàòèò <literal>7</literal> âìåñòî îæèäàåìîé <literal>8</literal> êàê ðåçóëüòàò âíóòðåííåãî ïðåäñòàâëåíèÿ ÷èñëà, ÿâëÿþùåãîñÿ â äåéñòâèòåëüíîñòè ÷åì-òî âðîäå <literal>7.9999999999...</literal>. </para> <para> Ýòî ñâÿçàíî ñ íåâîçìîæíîñòüþ òî÷íî âûðàçèòü íåêîòîðûå äðîáè â äåñÿòè÷íîé ñèñòåìå ñ÷èñëåíèÿ êîíå÷íûì ÷èñëîì öèôð. Íàïðèìåð, <literal>1/3</literal> â äåñÿòè÷íîé ôîðìå ïðèíèìàåò âèä <literal>0.3333333. . .</literal>. </para> <para> Òàê ÷òî íèêîãäà íå äîâåðÿéòå òî÷íîñòè ïîñëåäíèõ öèôð â ðåçóëüòàòàõ ñ ÷èñëàìè ñ ïëàâàþùåé òî÷êîé è íèêîãäà íå ïðîâåðÿéòå èõ íà ðàâåíñòâî. Åñëè âàì äåéñâèòåëüíî íåîáõîäèìà âûñîêàÿ òî÷íîñòü, âàì ñëåäóåò èñïîëüçîâàòü <link linkend="ref.bc">ìàòåìàòè÷åñêèå ôóíêöèè ïðîèçâîëüíîé òî÷íîñòè</link> èëè <link linkend="ref.gmp">gmp</link>-ôóíêöèè. </para> </warning> <sect2 id="language.types.float.casting"> <title>Êîíâåðòàöèÿ â ÷èñëî ñ ïëàâàþùåé òî÷êîé</title> <para> Î òîì êîãäà è êàê ñòðîêè êîíâåðòèðóþòñÿ â ÷èñëà ñ ïëàâàþùåé òî÷êîé ÷èòàéòå â ðàçäåëå <link linkend="language.types.string.conversion">Êîíâåðòàöèÿ ñòðîê â ÷èñëà</link>. Äëÿ çíà÷åíèé äðóãèõ òèïîâ êîíâåðòàöèÿ áóäåò òàêîé æå, êàê åñëè áû çíà÷åíèå ñíà÷àëà áûëî êîíâåðòèðîâàíî â öåëîå, à çàòåì â ÷èñëî ñ ïëàâàþùåé òî÷êîé. Äîïîëíèòåëüíóþ èíôîðìàöèþ ñìîòðèòå â ðàçäåëå <link linkend="language.types.integer.casting">Êîíâåðòàöèÿ â öåëîå</link>. </para> </sect2> </sect1> <sect1 id="language.types.string"> <title>Ñòðîêè</title> <para> Ñòðîêà - ýòî íàáîð ñèìâîëîâ.  PHP ñèìâîë ýòî òî æå ñàìîå, ÷òî è áàéò, ýòî çíà÷èò, ÷òî âîçìîæíî ðîâíî 256 ðàçëè÷íûõ ñèìâîëîâ. Ýòî òàêæå îçíà÷àåò, ÷òî PHP íå èìååò âñòðîåííîé ïîääåðæêè Unicode'à. Íåêîòîðóþ ïîääåðæêó Unicode'à îáåñïå÷èâàþò ýòè ôóíêöèè <function>utf8_enncode</function> è <function>utf8_decode</function>. </para> <note> <simpara> Íåò íèêàêèõ ïðîáëåì, åñëè ñòðîêà î÷åíü âåëèêà. Ïðàêòè÷åñêè íå ñóùåñòâóåò îãðàíè÷åíèé íà ðàçìåð ñòðîê, íàëàãàåìûõ PHP, òàê ÷òî íåò àáñîëþòíî íèêàêèõ ïðè÷èí áåñïîêîèòüñÿ îá èõ äëèíå. </simpara> </note> <sect2 id="language.types.string.syntax"> <title>Ñèíòàêñèñ</title> <para> Ñòðîêà ìîæåò áûòü îïðåäåëåíà òðåìÿ ðàçëè÷íûìè ñïîñîáàìè. <itemizedlist> <listitem> <simpara> <link linkend="language.types.string.syntax.single">îäèíàðíûìè êàâ÷êàìè</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.string.syntax.double">äâîéíûìè êàâû÷êàìè</link> </simpara> </listitem> <listitem> <simpara> <link linkend="language.types.string.syntax.heredoc">heredoc-ñèíòàêñèñîì</link> </simpara> </listitem> </itemizedlist> </para> <sect3 id="language.types.string.syntax.single"> <title>Îäèíàðíûå êàâû÷êè</title> <para> Ïðîñòåéøèé ñïîñîá îïðåäåëèòü ñòðîêó - ýòî çàêëþ÷èòü åå â îäèíàðíûå êàâû÷êè (ñèìâîë <literal>'</literal>). </para> <para> ×òîáû èñïîëüçîâàòü îäèíàðíóþ êàâû÷êó âíóòðè ñòðîêè, êàê è âî ìíîãèõ äðóãèõ ÿçûêàõ, åå íåîáõîäèìî ïðåäâàðèòü ñèìâîëîì îáðàòíîé êîñîé ÷åðòû (<literal>\</literal>), ò. å. ìíåìîíèçèðîâàòü åå. Åñëè îáðàòíàÿ íàêëîííàÿ ÷åðòà äîëæíà èäòè ïåðåä îäèíàðíîé êàâû÷êîé ëèáî áûòü â êîíöå ñòðîêè, âàì íåîáõîäèìî ïðîäóáëèðîâàòü åå. Îáðàòèòå âíèìàíèå, ÷òî åñëè âû ïîïûòàåòåñü ìíåìîíèçèðîâàòü ëþáîé äðóãîé ñèìâîë, îáðàòíàÿ êîñàÿ ÷åðòà òàêæå áóäåò íàïå÷àòàíà! Òàê ÷òî, êàê ïðàâèëî, íåò íåîáõîäèìîñòè ìíåìîíèçèðîâàòü ñàìó îáðàòíóþ êîñóþ ÷åðòó. <note> <simpara>  PHP 3 â äàííîì ñëó÷àå áóäåò âûäàíî ñîîáùåíèå óðîâíÿ <literal>E_NOTICE</literal>. </simpara> </note> <note> <simpara>  îòëè÷èå îò äâóõ äðóãèõ ñèíòàêñèñîâ, ïåðåìåííûå, âñòðå÷àþùèåñÿ â ñòðîêàõ, çàêëþ÷åííûõ â îäèíàðíûå êàâû÷êè, <emphasis>íå</emphasis> îáðàáàòûâàþòñÿ. </simpara> </note> <informalexample> <programlisting role="php"> <![CDATA[ echo ''ýòî ïðîñòàÿ ñòðîêà'; echo 'Âû ìîæåòå âñòàâëÿòü â ñòðîêè ñèìâîë íîâîé ñòðîêè òàêèì îáðàçîì'; echo 'Îäíàæäû Àðíîëüä ñêàçàë: "I\'ll be back"'; // âûâîä: ... "I'll be back" echo 'Âû óâåðåíû, ÷òî õîòèòå óäàëèòü C:\\*.*?'; // âûâîä: ... óäàëèòü C:\*.*? echo 'Âû óâåðåíû, ÷òî õîòèòå óäàëèòü C:\*.*?'; // âûâîä: ... óäàëèòü C:\*.*? echo 'ß ïûòàþñü âñòàâèòü â ýòîé òî÷êå: \n ñèìâîë íîâîé ñòðîêè'; // âûâîä: ... â ýòîé òî÷êå: \n ñèìâîë íîâîé ñòðîêè ]]> </programlisting> </informalexample> </para> </sect3> <sect3 id="language.types.string.syntax.double"> <title>Äâîéíûå êàâû÷êè</title> <para> Åñëè ñòðîêà çàêëþ÷åíà â äâîéíûå êàâû÷êè ("), PHP ðàñïîçíàåò áîëüøåå êîëè÷åñòâî ìíåìîíèê ñïåöèàëüíûõ ñèìâîëîâ: </para> <table> <title>Ìíåìîíèêè ñèìâîëîâ</title> <tgroup cols="2"> <thead> <row> <entry>ïîñëåäîâàòåëüíîñòü</entry> <entry>çíà÷åíèå</entry> </row> </thead> <tbody> <row> <entry><literal>\n</literal></entry> <entry>íîâàÿ ñòðîêà (LF èëè 0x0A (10) â ASCII)</entry> </row> <row> <entry><literal>\r</literal></entry> <entry>âîçâðàò êàðåòêè (CR èëè 0x0D (13) â ASCII)</entry> </row> <row> <entry><literal>\t</literal></entry> <entry>ãîðèçîíòàëüíàÿ òàáóëÿöèÿ (HT èëè 0x09 (9) â ASCII)</entry> </row> <row> <entry><literal>\\</literal></entry> <entry>îáðàòíàÿ íàêëîííàÿ ÷åðòà</entry> </row> <row> <entry><literal>\$</literal></entry> <entry>çíàê äîëëàðà</entry> </row> <row> <entry><literal>\"</literal></entry> <entry>äâîéíàÿ êàâû÷êà</entry> </row> <row> <entry><literal>\[0-7]{1,3}</literal></entry> <entry> ïîñëåäîâàòåëüíîñòü ñèìâîëîâ, ñîîòâåòñâóþùàÿ ðåãóëÿðíîìó âûðàæåíèþ, ñèìâîë â âîñüìåðè÷íîé ñèñòåìå ñ÷èñëåíèÿ </entry> </row> <row> <entry><literal>\x[0-9A-Fa-f]{1,2}</literal></entry> <entry> ïîñëåäîâàòåëüíîñòü ñèìâîëîâ, ñîîòâåòñâóþùàÿ ðåãóëÿðíîìó âûðàæåíèþ, ñèìâîë â øåñòíàäöàòåðè÷íîé ñèñòåìå ñ÷èñëåíèÿ </entry> </row> </tbody> </tgroup> </table> <para> Ïîâòîðÿåì, åñëè âû çàõîòèòå ìíåìíîíèçèðîâàòü ëþáîé äðóãîé ñèìâîë, îáðàòíàÿ êîñàÿ ÷åðòà òàêæå áóäåò íàïå÷àòàíà! </para> <para> Íî ñàìûì âàæíûì ñâîéñòâîì ñòðîê â äâîéíûõ êàâû÷êàõ ÿâëÿåòñÿ îáðàáîòêà ïåðåìåííûõ. Ñìîòðèòå áîëåå ïîäðîáíî: <link linkend="language.types.string.parsing">îáðàáîòêà ñòðîê</link>. </para> </sect3> <sect3 id="language.types.string.syntax.heredoc"> <title>Heredoc</title> <simpara> Äðóãîé ñïîñîá îïðåäåëåíèÿ ñòðîê - ýòî èñïîëüçîâàíèå heredoc-ñèíòàêñèñà ("<<<"). One should provide an identifier after <literal><<<</literal>, then the string, and then the same identifier to close the quotation. </simpara> <simpara> The closing identifier <emphasis>must</emphasis> begin in the first column of the line. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore. </simpara> <warning> <simpara> It is very important to note that the line with the closing identifier contains no other characters, except <emphasis>possibly</emphasis> a semicolon (<literal>;</literal>). That means especially that the identifier <emphasis>may not be indented</emphasis>, and there may not be any spaces or tabs after or before the semicolon. </simpara> </warning> <para> Heredoc text behaves just like a double-quoted string, without the double-quotes. This means that you do not need to escape quotes in your here docs, but you can still use the escape codes listed above. Variables are expanded, but the same care must be taken when expressing complex variables inside a here doc as with strings. <example> <title>Heredoc string quoting example</title> <programlisting role="php"> <![CDATA[ <?php $str = <<<EOD Example of string spanning multiple lines using heredoc syntax. EOD; /* More complex example, with variables. */ class foo { var $foo; var $bar; function foo() { $this->foo = 'Foo'; $this->bar = array('Bar1', 'Bar2', 'Bar3'); } } $foo = new foo(); $name = 'MyName'; echo <<<EOT My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should print a capital 'A': \x41 EOT; ?> ]]> </programlisting> </example> </para> <note> <para> Heredoc support was added in PHP 4. </para> </note> </sect3> <sect3 id="language.types.string.parsing"> <title>Variable parsing</title> <simpara> When a string is specified in double quotes or with heredoc, variables are parsed within it. </simpara> <simpara> There are two types of syntax, a <link linkend="language.types.string.parsing.simple">simple</link> one and a <link linkend="language.types.string.parsing.complex">complex</link> one. The simple syntax is the most common and convenient, it provides a way to parse a variable, an array value, or an object property. </simpara> <simpara> The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression. </simpara> <sect4 id="language.types.string.parsing.simple"> <title>Simple syntax</title> <simpara> If a dollar sign (<literal>$</literal>) is encountered, the parser will greedily take as much tokens as possible to form a valid variable name. Enclose the variable name in curly braces if you want to explicitly specify the end of the name. </simpara> <informalexample> <programlisting role="php"> <![CDATA[ $beer = 'Heineken'; echo "$beer's taste is great"; // works, "'" is an invalid character for varnames echo "He drank some $beers"; // won't work, 's' is a valid character for varnames echo "He drank some ${beer}s"; // works ]]> </programlisting> </informalexample> <simpara> Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (<literal>]</literal>) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables. <!-- XXX isn't &true; :(, this would be the trick Also, the same trick with curly-braces works if you want to limit the greediness of parsers. --> </simpara> <informalexample> <programlisting role="php"> <![CDATA[ $fruits = array('strawberry' => 'red', 'banana' => 'yellow'); // note that this works differently outside string-quotes echo "A banana is $fruits[banana]."; echo "This square is $square->width meters broad."; // Won't work. For a solution, see the complex syntax. echo "This square is $square->width00 centimeters broad."; ]]> <!-- XXX this won't work: echo "This square is $square->{width}00 centimeters broad."; // XXX: php developers: it would be consequent to make this work. // XXX: like the $obj->{expr} syntax outside a string works, // XXX: analogously to the ${expr} syntax for variable var's. --> </programlisting> </informalexample> <simpara> For anything more complex, you should use the complex syntax. </simpara> </sect4> <sect4 id="language.types.string.parsing.complex"> <title>Complex (curly) syntax</title> <simpara> This isn't called complex because the syntax is complex, but because you can include complex expressions this way. </simpara> <simpara> In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can't escape '{', this syntax will only be recognised when the $ is immediately following the {. (Use "{\$" or "\{$" to get a literal "{$"). Some examples to make it clear: </simpara> <informalexample> <programlisting role="php"> <![CDATA[ $great = 'fantastic'; echo "This is { $great}"; // won't work, outputs: This is { fantastic} echo "This is {$great}"; // works, outputs: This is fantastic echo "This square is {$square->width}00 centimeters broad."; echo "This works: {$arr[4][3]}"; // This is wrong for the same reason // as $foo[bar] is wrong outside a string. echo "This is wrong: {$arr[foo][3]}"; echo "You should do it this way: {$arr['foo'][3]}"; echo "You can even write {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; ]]> <!-- maybe it's better to leave this out?? // this works, but i disencourage its use, since this is NOT // involving functions, rather than mere variables, arrays and objects. $beer = 'Heineken'; echo "I'd like to have another {${ strrev('reeb') }}, hips"; --> </programlisting> </informalexample> </sect4> </sect3> <sect3 id="language.types.string.substr"> <title>String access by character</title> <para> Characters within strings may be accessed by specifying the zero-based offset of the desired character after the string in curly braces. </para> <note> <simpara> For backwards compatibility, you can still use array-braces for the same purpose. However, this syntax is deprecated as of PHP 4. </simpara> </note> <para> <example> <title>Some string examples</title> <programlisting role="php"> <![CDATA[ <?php // Get the first character of a string $str = 'This is a test.'; $first = $str{0}; // Get the last character of a string. $str = 'This is still a test.'; $last = $str{strlen($str)-1}; ?> ]]> </programlisting> </example> </para> </sect3> </sect2><!-- end syntax --> <sect2 id="language.types.string.useful-funcs"> <title>Useful functions and operators</title> <para> Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see <link linkend="language.operators.string">String operators</link> for more information. </para> <para> There are a lot of useful functions for string modification. </para> <simpara> See the <link linkend="ref.strings">string functions section</link> for general functions, the regular expression functions for advanced find&replacing (in two tastes: <link linkend="ref.pcre">Perl</link> and <link linkend="ref.regex">POSIX extended</link>). </simpara> <simpara> There are also <link linkend="ref.url">functions for URL-strings</link>, and functions to encrypt/decrypt strings (<link linkend="ref.mcrypt">mcrypt</link> and <link linkend="ref.mhash">mhash</link>). </simpara> <simpara> Finally, if you still didn't find what you're looking for, see also the <link linkend="ref.ctype">character type functions</link>. </simpara> </sect2> <sect2 id="language.types.string.casting"> <title>Converting to string</title> <para> You can convert a value to a string using the <literal>(string)</literal> cast, or the <function>strval</function> function. String conversion is automatically done in the scope of an expression for you where a string is needed. This happens when you use the <function>echo</function> or <function>print</function> functions, or when you compare a variable value to a string. </para> <para> A boolean &true; value is converted to the string <literal>"1"</literal>, the &false; value is represented as <literal>""</literal> (empty string). This way you can convert back and forth between boolean and string values. </para> <para> An integer or a floating point number is converted to a string representing the number with its digits (includig the exponent part for floating point numbers). </para> <para> Arrays are always converted to the string <literal>"Array"</literal>, so you cannot dump out the contents of an array with <function>echo</function> or <function>print</function> to see what is inside them. See the information below for more tips. </para> <para> Objects are always converted to the string <literal>"Object"</literal>. If you would like to print out the member variable values of an object for debugging reasons, read the paragraphs below. If you would like to find out the class name of which an object is an instance of, use <function>get_class</function>. </para> <para> Resources are always converted to strings with the structure <literal>"Resource id #1"</literal> where <literal>1</literal> is the unique number of the resource assigned by PHP during runtime. If you would like to get the type of the resource, use <function>get_resource_type</function>. </para> <para> &null; is always converted to an empty string. </para> <para> As you can see above, printing out the arrays, objects or resources does not provide you any useful information about the values themselfs. Look at the functions <function>print_r</function> and <function>var_dump</function> for better ways to print out values for debugging. </para> <para> You can also convert PHP values to strings to store them permanently. This method is called serialization, and can be done with the function <function>serialize</function>. You can also serialize PHP values to XML structures, if you have <link linkend="ref.wddx">WDDX</link> support in your PHP setup. </para> </sect2> <sect2 id="language.types.string.conversion"> <title>String conversion to numbers</title> <simpara> When a string is evaluated as a numeric value, the resulting value and type are determined as follows. </simpara> <simpara> The string will evaluate as a <type>float</type> if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer. </simpara> <para> The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits. </para> <informalexample> <programlisting role="php"> <![CDATA[ $foo = 1 + "10.5"; // $foo is float (11.5) $foo = 1 + "-1.3e3"; // $foo is float (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) $foo = "10.0 pigs " + 1; // $foo is float (11) $foo = "10.0 pigs " + 1.0; // $foo is float (11) ]]> </programlisting> </informalexample> <simpara> For more information on this conversion, see the Unix manual page for strtod(3). </simpara> <para> If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on: <informalexample> <programlisting role="php"> <![CDATA[ echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n"; ]]> </programlisting> </informalexample> </para> <para> Do not expect to get the code of one character by converting it to integer (as you would do in C for example). Use the functions <function>ord</function> and <function>chr</function> to convert between charcodes and characters. </para> </sect2> </sect1><!-- end string --> <sect1 id="language.types.array"> <title>Arrays</title> <para> An array in PHP is actually an ordered map. A map is a type that maps <emphasis>values</emphasis> to <emphasis>keys</emphasis>. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP-array as a value, you can also quite easily simulate trees. </para> <para> Explanation of those structures is beyond the scope of this manual, but you'll find at least one example for each of those structures. For more information we refer you to external literature about this broad topic. </para> <sect2 id="language.types.array.syntax"> <title>Syntax</title> <sect3 id="language.types.array.syntax.array-func"> <title>Specifying with <function>array</function></title> <para> An <type>array</type> can be created by the <function>array</function> language-construct. It takes a certain number of comma-separated <literal><replaceable>key</replaceable> => <replaceable >value</replaceable></literal> pairs. </para> <para> <synopsis> array( <optional> <replaceable>key</replaceable> => </optional> <replaceable >value</replaceable> , ... ) // <replaceable>key</replaceable> is either <type>string</type > or nonnegative <type>integer</type> // <replaceable>value</replaceable> can be anything </synopsis> </para> <para> <informalexample> <programlisting role="php"> <![CDATA[ array("foo" => "bar", 12 => true); ]]> </programlisting> </informalexample> </para> <para> A <varname>key</varname> is either an <type>integer</type> or a <type>string</type>. If a key is the standard representation of an <type>integer</type>, it will be interpreted as such (i.e. <literal>"8"</literal> will be interpreted as <literal>8</literal>, while <literal>"08"</literal> will be interpreted as <literal>"08"</literal>). There are no different indexed and associative array types in PHP, there is only one array type, which can both contain integer and string indices. </para> <para> A value can be of any PHP type. <informalexample> <programlisting role="php"> <![CDATA[ array("somearray" => array(6 => 5, 13 => 9, "a" => 43)); ]]> </programlisting> </informalexample> </para> <para> If you omit a key, the maximum of the integer-indices is taken, and the new key will be that maximum + 1. As integers can be negative, this is also true for negative indices. Having e.g. the highest index being <literal>-6</literal> will result in being <literal>-5</literal> the new key. If no integer-indices exist yet, the key will be <literal>0</literal> (zero). If you specify a key that already has a value assigned to it, that value will be overwritten. <informalexample> <programlisting role="php"> <![CDATA[ // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ]]> </programlisting> </informalexample> </para> <para> Using &true; as a key will evalute to <type>integer</type> <literal>1</literal> as key. Using &false; as a key will evalute to <type>integer</type> <literal>0</literal> as key. Using <literal>NULL</literal> as a key will evaluate to an empty string. Using an emptry string as key will create (or overwrite) a key with an empty string and its value, it is not the same as using empty brackets. </para> <para> You cannot use arrays or objects as keys. Doing so will result in a warning: <literal>Illegal offset type</literal>. </para> </sect3> <sect3 id="language.types.array.syntax.modifying"> <title>Creating/modifying with square-bracket syntax</title> <para> You can also modify an existing array, by explicitly setting values in it. </para> <para> This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("<literal>[]</literal>") to the variable-name in that case. <synopsis> $arr[<replaceable>key</replaceable>] = <replaceable>value</replaceable>; $arr[] = <replaceable>value</replaceable>; // <replaceable>key</replaceable> is either <type>string</type > or nonnegative <type>integer</type> // <replaceable>value</replaceable> can be anything </synopsis> If <varname>$arr</varname> doesn't exist yet, it will be created. So this is also an alternative way to specify an array. To change a certain value, just assign a new value to an element specified with its key. If you want to remove a key/value pair, you need to <function>unset</function> it. <informalexample> <programlisting role="php"> <![CDATA[ $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ]]> </programlisting> </informalexample> </para> </sect3> </sect2><!-- end syntax --> <sect2 id="language.types.array.useful-funcs"> <title>Useful functions</title> <para> There are quite some useful function for working with arrays, see the <link linkend="ref.array">array functions</link> section. </para> <note> <para> The <function>unset</function> function allows unsetting keys of an array. Be aware that the array will NOT be reindexed. If you only use "usual integer indices" (starting from zero, increasing by one), you can achive the reindex effect by using <function>array_values</function>. <informalexample> <programlisting role="php"> <![CDATA[ $a = array(1 => 'one', 2 => 'two', 3 => 'three'); unset($a[2]); /* will produce an array that would have been defined as $a = array(1 => 'one', 3 => 'three'); and NOT $a = array(1 => 'one', 2 =>'three'); */ $b = array_values($a); // Now b is array(1 => 'one', 2 =>'three') ]]> </programlisting> </informalexample> </para> </note> <para> The <link linkend="control-structures.foreach">foreach</link> control structure exists specifically for arrays. It provides an easy way to traverse an array. </para> </sect2> <sect2 id="language.types.array.donts"> <title>Array do's and don'ts</title> <sect3 id="language.types.array.foo-bar"> <title>Why is <literal>$foo[bar]</literal> wrong?</title> <para> You should always use quotes around an associative array index. For example, use $foo['bar'] and not $foo[bar]. But why is $foo[bar] wrong? You might have seen the following syntax in old scripts: <informalexample> <programlisting role="php"> <![CDATA[ $foo[bar] = 'enemy'; echo $foo[bar]; // etc ]]> </programlisting> </informalexample> This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works, because the undefined constant gets converted to a string of the same name automatically for backward compatibility reasons. </para> <para> As stated in the <link linkend="language.types.array.syntax" >syntax</link> section, there must be an expression between the square brackets ('<literal>[</literal>' and '<literal>]</literal>'). That means that you can write things like this: <informalexample> <programlisting role="php"> <![CDATA[ echo $arr[foo(true)]; ]]> </programlisting> </informalexample> This is an example of using a function return value as the array index. PHP also knows about constants, as you may have seen the <literal>E_*</literal> ones before. <informalexample> <programlisting role="php"> <![CDATA[ $error_descriptions[E_ERROR] = "A fatal error has occured"; $error_descriptions[E_WARNING] = "PHP issued a warning"; $error_descriptions[E_NOTICE] = "This is just an informal notice"; ]]> </programlisting> </informalexample> Note that <literal>E_ERROR</literal> is also a valid identifier, just like <literal>bar</literal> in the first example. But the last example is in fact the same as writing: <informalexample> <programlisting role="php"> <![CDATA[ $error_descriptions[1] = "A fatal error has occured"; $error_descriptions[2] = "PHP issued a warning"; $error_descriptions[8] = "This is just an informal notice"; ]]> </programlisting> </informalexample> because <literal>E_ERROR</literal> equals <literal>1</literal>, etc. </para> <para> Then, how is it possible that <literal>$foo[bar]</literal> works? It works, because <literal>bar</literal> is due to its syntax expected to be a constant expression. However, in this case no constant with the name <literal>bar</literal> exists. PHP now assumes that you meant <literal>bar</literal> literally, as the string <literal>"bar"</literal>, but that you forgot to write the quotes. </para> <sect4> <title>So why is it bad then?</title> <para> At some point in the future, the PHP team might want to add another constant or keyword, or you may introduce another constant into your application, and then you get in trouble. For example, you already cannot use the words <literal>empty</literal> and <literal>default</literal> this way, since they are special <link linkend="reserved">reserved keywords</link>. </para> <note> <para> When you turn <link linkend="function.error-reporting" >error_reporting</link> to <literal>E_ALL</literal>, you will see that PHP generates notices whenever an <literal>index</literal> is used which is not defined. Consider this script: <informalexample> <programlisting role="php"> <![CDATA[ <?php // Turn on the display of all errors error_reporting(E_ALL); // Define the test array $abc = array("x" => "y"); // Access element with the *bad* method echo $abc[x]; ?> ]]> </programlisting> </informalexample> The output is: <informalexample> <programlisting> <![CDATA[ <br /> <b>Notice</b>: Use of undefined constant x - assumed 'x' in <b>/path/to/script.php</b> on line <b>10</b><br /> ]]> </programlisting> </informalexample> </para> </note> <note> <simpara> Inside a double-quoted <type>string</type>, another syntax is valid. See <link linkend="language.types.string.parsing" >variable parsing in strings</link> for more details. </simpara> </note> </sect4> </sect3> </sect2> <sect2 id="language.types.array.casting"> <title>Converting to array</title> <para> For any of the types: integer, float, string, boolean and resource, if you convert a value to an array, you get an array with one element (with index 0), which is the scalar value you started with. </para> <para> If you convert an object to an array, you get the properties (member variables) of that object as the array's elements. The keys are the member variable names. </para> <para> If you convert a &null; value to an array, you get an empty array. </para> </sect2> <sect2 id="language.types.array.examples"> <title>Examples</title> <para> The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays. </para> <para> <informalexample> <programlisting role="php"> <![CDATA[ // this $a = array( 'color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 'name' => 'apple', 4 // key will be 0 ); // is completely equivalent with $a['color'] = 'red'; $a['taste'] = 'sweet'; $a['shape'] = 'round'; $a['name'] = 'apple'; $a[] = 4; // key will be 0 $b[] = 'a'; $b[] = 'b'; $b[] = 'c'; // will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'), // or simply array('a', 'b', 'c') ]]> </programlisting> </informalexample> </para> <example> <title>Using array()</title> <programlisting role="php"> <![CDATA[ // Array as (property-)map $map = array( 'version' => 4, 'OS' => 'Linux', 'lang' => 'english', 'short_tags' => true ); // strictly numerical keys $array = array( 7, 8, 0, 156, -10 ); // this is the same as array(0 => 7, 1 => 8, ...) $switching = array( 10, // key = 0 5 => 6, 3 => 7, 'a' => 4, 11, // key = 6 (maximum of integer-indices was 5) '8' => 2, // key = 8 (integer!) '02' => 77, // key = '02' 0 => 12 // the value 10 will be overwritten by 12 ); // empty array $empty = array(); ]]> <!-- TODO example of - overwriting keys - using vars/functions as key/values - warning about references --> </programlisting> </example> <example id="language.types.array.examples.loop"> <title>Collection</title> <programlisting role="php"> <![CDATA[ $colors = array('red', 'blue', 'green', 'yellow'); foreach ($colors as $color) { echo "Do you like $color?\n"; } /* output: Do you like red? Do you like blue? Do you like green? Do you like yellow? */ ]]> </programlisting> </example> <para> Note that it is currently not possible to change the values of the array directly in such a loop. <!-- Should be made possible, if you write: foreach ( $colors as &$color ) See bug#3074 --> A workaround is the following: <example id="language.types.array.examples.changeloop"> <title>Collection</title> <programlisting role="php"> <![CDATA[ foreach ($colors as $key => $color) { // won't work: //$color = strtoupper($color); // works: $colors[$key] = strtoupper($color); } print_r($colors); /* output: Array ( [0] => RED [1] => BLUE [2] => GREEN [3] => YELLOW ) */ ]]> </programlisting> </example> </para> <para> This example creates a one-based array. <example> <title>One-based index</title> <programlisting role="php"> <![CDATA[ $firstquarter = array(1 => 'January', 'February', 'March'); print_r($firstquarter); /* output: Array ( [1] => 'January' [2] => 'February' [3] => 'March' ) */ ]]> </programlisting> </example> </para> <example> <title>Filling an array</title> <programlisting role="php"> <![CDATA[ // fill an array with all items from a directory $handle = opendir('.'); while ($file = readdir($handle)) { $files[] = $file; } closedir($handle); ]]> </programlisting> </example> <para> Arrays are ordered. You can also change the order using various sorting-functions. See the <link linkend="ref.array">array functions</link> section for more information. You can count the number of items in an array using the <function>count</function> function. </para> <example> <title>Sorting array</title> <programlisting role="php"> <![CDATA[ sort($files); print_r($files); ]]> </programlisting> </example> <para> Because the value of an array can be everything, it can also be another array. This way you can make recursive and multi-dimensional arrays. </para> <example> <title>Recursive and multi-dimensional arrays</title> <programlisting role="php"> <![CDATA[ $fruits = array ( "fruits" => array ( "a" => "orange", "b" => "banana", "c" => "apple" ), "numbers" => array ( 1, 2, 3, 4, 5, 6, ), "holes" => array ( "first", 5 => "second", "third" ) ); // Some examples to address values in the array above echo $fruits["holes"][5]; // prints "second" echo $fruits["fruits"]["a"]; // prints "orange" unset($fruits["holes"][0]); // remove "first" // Create a new multi-dimensional array $juices["apple"]["green"] = "good"; ]]> </programlisting> </example> <para> You should be aware, that array assignment always involves value copying. You need to use the reference operator to copy an array by reference. <informalexample> <programlisting role="php"> <![CDATA[ $arr1 = array(2, 3); $arr2 = $arr1; $arr2[] = 4; // $arr2 is changed, // $arr1 is still array(2,3) $arr3 = &$arr1; $arr3[] = 4; // now $arr1 and $arr3 are the same ]]> </programlisting> </informalexample> </para> </sect2> </sect1> <sect1 id="language.types.object"> <title>Objects</title> <sect2 id="language.types.object.init"> <title>Object Initialization</title> <para> To initialize an object, you use the <literal>new</literal> statement to instantiate the object to a variable. <informalexample> <programlisting role="php"> <![CDATA[ <?php class foo { function do_foo() { echo "Doing foo."; } } $bar = new foo; $bar->do_foo(); ?> ]]> </programlisting> </informalexample> </para> <simpara> For a full discussion, please read the section <link linkend="language.oop">Classes and Objects</link>. </simpara> </sect2> <sect2 id="language.types.object.casting"> <title>Converting to object</title> <para> If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instace of the <literal>stdClass</literal> built in class is created. If the value was null, the new instance will be empty. For any other value, a member variable named <literal>scalar</literal> will contain the value. <informalexample> <programlisting role="php"> $obj = (object) 'ciao'; echo $obj->scalar; // outputs 'ciao' </programlisting> </informalexample> </para> </sect2> </sect1> <sect1 id="language.types.resource"> <title>Resource</title> <para> A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the <link linkend="resource">appendix</link> for a listing of all these functions and the corresponding resource types. </para> <note> <simpara> The resource type was introduced in PHP 4 </simpara> </note> <sect2 id="language.types.resource.casting"> <title>Converting to resource</title> <para> As resource types hold special handlers to opened files, database connections, image canvas areas and the like, you cannot convert any value to a resource. </para> </sect2> <sect2 id="language.types.resource.self-destruct"> <title>Freeing resources</title> <para> Due to the reference-counting system introduced with PHP4's Zend-engine, it is automatically detected when a resource is no longer referred to (just like Java). When this is the case, all resources that were in use for this resource are made free by the garbage collector. For this reason, it is rarely ever necessary to free the memory manually by using some free_result function. <note> <simpara> Persistent database links are special, they are <emphasis>not</emphasis> destroyed by the garbage collector. See also the section about <link linkend="features.persistent-connections">persistent connections</link>. </simpara> </note> </para> </sect2> </sect1> <sect1 id="language.types.null"> <title>NULL</title> <para> The special &null; value represents that a variable has no value. &null; is the only possible value of type <type>NULL</type>. </para> <note> <simpara> The null type was introduced in PHP 4 </simpara> </note> <para> A variable is considered to be &null; if <itemizedlist> <listitem> <para> it has been assigned the constant &null;. </para> </listitem> <listitem> <para> it has not been set to any value yet. </para> </listitem> <listitem> <para> it has been <function>unset</function>. </para> </listitem> </itemizedlist> </para> <sect2 id="language.types.null.syntax"> <title>Syntax</title> <para> There is only one value of type &null;, and that is the case-insensitive keyword &null;. <informalexample> <programlisting role="php"> $var = NULL; </programlisting> </informalexample> </para> <para> See also <function>is_null</function> and <function>unset</function>. </para> </sect2> </sect1> <sect1 id="language.pseudo-types"> <title>Pseudo-types used in this documentation</title> <sect2 id="language.types.mixed"> <title>mixed</title> <para> <literal>mixed</literal> indicates that a parameter may accept multiple (but not necesseraly all) types. </para> <para> <function>gettype</function> for example will accept all PHP types, while <function>str_replace</function> will accept strings and arrays. </para> </sect2> <sect2 id="language.types.number"> <title>number</title> <para> <literal>number</literal> indicates that a parameter can be either <type>integer</type> or <type>float</type>. </para> </sect2> <sect2 id="language.types.callback"> <title>callback</title> <para> Some functions like <function>call_user_function</function> or <function>usort</function> accept user defined callback functions as a parameter. Callback functions can not only be simple functions but also object methods including static class methods. </para> <para> A PHP function is simply passed by its name as a string. You can pass any builtin or user defined function with the exception of <function>array</function>, <function>echo</function>, <function>empty</function>, <function>eval</function>, <function>exit</function>, <function>isset</function>, <function>list</function>, <function>print</function> and <function>unset</function>. </para> <para> A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1. </para> <para> Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object as the element with index 0. </para> <para> <example> <title> Callback function examples </title> <programlisting role="php"> <![CDATA[ <?php // simple callback example function foobar() { echo "hello world!"; } call_user_function("foobar"); // method callback examples class foo { function bar() { echo "hello world!"; } } $foo = new foo; call_user_function(array($foo, "bar")); // object method call call_user_function(array("foo", "bar")); // static class method call ?> ]]> </programlisting> </example> </para> </sect2> </sect1> <sect1 id="language.types.type-juggling"> <title>Type Juggling</title> <simpara> PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable <parameter>$var</parameter>, <parameter>$var</parameter> becomes a string. If you then assign an integer value to <parameter>$var</parameter>, it becomes an integer. </simpara> <para> An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated. <informalexample> <programlisting role="php"> $foo = "0"; // $foo is string (ASCII 48) <!-- bad example, no real operator (must be used with variable, modifies it too) $foo++; // $foo is the string "1" (ASCII 49) --> $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) <!-- TODO: explain ++/- - behaviour with strings examples: ++'001' = '002' ++'abc' = 'abd' ++'xyz' = 'xza' ++'9.9' = '9.0' ++'-3' = '-4' - -'9' = 8 (integer!) - -'5.5' = '5.5' - -'-9' = -10 (integer) - -'09' = 8 (integer) - -'abc' = 'abc' --> </programlisting> </informalexample> </para> <simpara> If the last two examples above seem odd, see <link linkend="language.types.string.conversion">String conversion to numbers</link>. </simpara> <simpara> If you wish to force a variable to be evaluated as a certain type, see the section on <link linkend="language.types.typecasting">Type casting</link>. If you wish to change the type of a variable, see <function>settype</function>. </simpara> <para> If you would like to test any of the examples in this section, you can use the <function>var_dump</function> function. </para> <note> <para> The behaviour of an automatic conversion to array is currently undefined. </para> <para> <informalexample> <programlisting role="php"> $a = "1"; // $a is a string $a[0] = "f"; // What about string offsets? What happens? </programlisting> </informalexample> </para> <para> Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a? </para> <para> The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes "f", the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above: <informalexample> <programlisting role="php"> $a = "abc"; // $a is a string $a{1} = "f"; // $a is now "afc" </programlisting> </informalexample> See the section titled <link linkend="language.types.string.substr">String access by character</link> for more informaton. </para> </note> <sect2 id="language.types.typecasting"> <title>Type Casting</title> <para> Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast. <informalexample> <programlisting role="php"> $foo = 10; // $foo is an integer $bar = (boolean) $foo; // $bar is a boolean </programlisting> </informalexample> </para> <para> The casts allowed are: <itemizedlist> <listitem> <simpara>(int), (integer) - cast to integer</simpara> </listitem> <listitem> <simpara>(bool), (boolean) - cast to boolean</simpara> </listitem> <listitem> <simpara>(float), (double), (real) - cast to float</simpara> </listitem> <listitem> <simpara>(string) - cast to string</simpara> </listitem> <listitem> <simpara>(array) - cast to array</simpara> </listitem> <listitem> <simpara>(object) - cast to object</simpara> </listitem> </itemizedlist> </para> <para> Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent: <informalexample> <programlisting role="php"> $foo = (int) $bar; $foo = ( int ) $bar; </programlisting> </informalexample> </para> <note> <para> Instead of casting a variable to string, you can also enclose the variable in double quotes. <informalexample> <programlisting role="php"> $foo = 10; // $foo is an integer $str = "$foo"; // $str is a string $fst = (string) $foo; // $fst is also a string // This prints out that "they are the same" if ($fst === $str) { echo "they are the same"; } </programlisting> </informalexample> </para> </note> <para> It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections: <itemizedlist> <listitem> <simpara><link linkend="language.types.boolean.casting">Converting to boolean</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.integer.casting">Converting to integer</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.float.casting">Converting to float</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.string.casting">Converting to string</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.array.casting">Converting to array</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.object.casting">Converting to object</link></simpara> </listitem> <listitem> <simpara><link linkend="language.types.resource.casting">Converting to resource</link></simpara> </listitem> <!-- don't exist yet <listitem> <simpara><link linkend="language.types.null.casting">Converting to &null;</link></simpara> </listitem> --> </itemizedlist> </para> </sect2> </sect1> </chapter> <!-- 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:"../../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 -->