对php中类中函数的作用域的理解

    技术2022-05-20  34

    1   php中的函数真的很恶心以至于函数中任何变量,只要不是特别指明都是局部变量!!!!

     

    2   举一个在类中的例子,代码如下:

     

    <?php

     

      class Test()

    {

                protected $meng = 'meng';

                function test(){

     

                       echo $this->meng;

                }

    }

    $jack = new Test;

    $jack->test();

     

     

    ?>

     

    这里test函数里面必须是这么调用$this->meng;否则就把它当做函数的局部变量了。。。囧。。

     

    3  代码如下:

     

    class Test()

    {

                function test(){

     

                       echo "hello world";

                }

    }

    Test::test();

     

    类中的函数完全可以这样调用。。php太假了。。。

     

    4

    <?php class  SimpleClass {      // 无效的类成员定义:      public  $var1  'hello ' . 'world' ;     public  $var2  = <<<EOD hello world EOD;     public  $var3  1 + 2 ;     public  $var4  self :: myStaticMethod ();     public  $var5  $myVar ;      // 正确的类成员定义:      public  $var6  myConstant ;     public  $var7  self :: classConstant ;     public  $var8  = array( true false ); } ?> 可以看到类成员定义必须是常量! 5 定义一个常量 <?php class  MyClass {     const  constant  'constant value' ;     function  showConstant () {         echo   self :: constant  "/n" ;     } } echo  MyClass :: constant  "/n" ; php太假了。。。 6

    最新回复(0)