首頁 >後端開發 >php教程 >PHP變數及變數作用域 php列印變數 php的變數與常數 php所有變

PHP變數及變數作用域 php列印變數 php的變數與常數 php所有變

WBOY
WBOY原創
2016-07-29 08:49:171129瀏覽

   新學PHP,比較有趣的文法,記錄下。

1. 變數的作用域

   作用域只分兩個Global和Local,Global相對於整個.php檔案來講,Local是本地最小範圍,是距離變數最近的範圍,如:在函數中,在類中等。

2. 變數的宣告

    可能是由於PHP變數獨特的$符號,所以聲明PHP變數不需要關鍵字(類別中除外),第一次賦值的時候自動建立了。

    類別中卻比較獨特了,由於類別帶有成員屬性private、public、protected,那麼在類別中宣告變數的時候是需要關鍵字修飾的。用前面所說的關鍵字或這個關鍵字var,但是不可以二者共用。

3. 範例說明

<span> 1</span> <?<span>php
</span><span> 2</span><span> 3</span><span>$VarFile</span> = "Var_File";   <span>//</span><span>变量声明</span><span> 4</span><span> 5</span><span>$nr</span> = <span>array</span>("\n","\r","\n\r","\r\n"<span>);
</span><span> 6</span><span> 7</span><span> 8</span><span>class</span><span> TestClass
</span><span> 9</span><span>{    
</span><span>10</span><span>/*</span><span>11</span><span>    *    分别用Var声明和private关键字声明
</span><span>12</span><span>    *   $var = value; 这种不可以
</span><span>13</span><span>    *    var private $var; 这种不可以
</span><span>14</span><span>    *    var private $var = value; 这种不可以
</span><span>15</span><span>    *    var $var; 这种不可以    
</span><span>16</span><span>*/</span><span>17</span><span>18</span><span>var</span><span>$VarClass</span> = 'VarClass declared by keyword Var'<span>;            
</span><span>19</span><span>private</span><span>$VarClass2</span> = 'VarClass2 declared by keyword private'<span>;
</span><span>20</span><span>21</span><span>/*</span><span>22</span><span>    *    增加global关键字,使用global作用域的变量
</span><span>23</span><span>    *   函数中声明变量方法与全局一样
</span><span>24</span><span>*/</span><span>25</span><span>26</span><span>function</span><span> GetAllVar() {
</span><span>27</span><span>global</span><span>$VarFile</span><span>;
</span><span>28</span><span>$VarFunction</span> = 'Var_Function'<span>;
</span><span>29</span><span>30</span><span>$Temp</span> = "<span>$VarFile</span>=".<span>$VarFile</span>."\r\n".
<span>31</span>                 "VarClass=".<span>$this</span>->VarClass."\r\n".
<span>32</span>                 "VarClass2=".<span>$this</span>->VarClass2."\r\n".
<span>33</span>                 "VarFunction=".<span>$VarFunction</span>."\r\n"<span>;
</span><span>34</span><span>35</span><span>36</span><span>return</span><span>str_replace</span>(<span>$GLOBALS</span>['nr'],"<br/>",<span>$Temp</span><span>);
</span><span>37</span><span>    }
</span><span>38</span><span>39</span><span>40</span><span>41</span><span>}
</span><span>42</span><span>43</span><span>$MyClass</span> = <span>new</span> TestClass("zzy"<span>);
</span><span>44</span><span>echo</span><span>$MyClass</span>-><span>GetAllVar();
</span><span>45</span><span>46</span> ?>

  

以上就介紹了PHP變數及變數作用域,包括了php,變數方面的內容,希望對PHP教學有興趣的朋友有幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn