doubi1624 2013-10-06 02:32
浏览 56
已采纳

是否可以在课堂外更改课程的属性? (PHP)

I'm quite inexperienced with OOP PHP but here's my question...let's say I have this class with one property:

class myClass {

    public $property = array();

    public function getProperty() {
        return $this->property;
    }

}

How would it be possible to change the value of $property without altering the class itself in any way, or by instantiating an object out of it, then changing its property. Is there any other way of doing it? Using scope resolution?

Hope that makes sense, any help would be much appreciated.

  • 写回答

2条回答 默认 最新

  • duanbiao4025 2013-10-06 02:48
    关注

    What you want is a static member

    class MyClass {
       public static $MyStaticMember = 0;
    
       public function echoStaticMember() {
          echo MyClass::$MyStaticMember;
          //note you can use self instead of the class name when inside the class
          echo self::$MyStaticMember;
       }
    
       public function incrementStaticMember() {
          self::$MyStaticMember++;
       }
    }
    

    then you access it like

    MyClass::$MyStaticMember = "Some value"; //Note you use the $ with the variable name
    

    Now any instances and everything will see the same value for whatever the static member is set to so take for instance the following

    function SomeMethodInAFarFarAwayScript() {
       echo MyClass::$MyStaticMember;
    } 
    
    ...
    
    MyClass::$MyStaticMember++; //$MyStaticMember now is: 1
    
    $firstClassInstance = new MyClass();
    
    echo MyClass::$MyStaticMember; //will echo: 1
    $firstClassInstance->echoStaticMember(); //will echo: 1
    
    $secondInstance = new MyClass();
    $secondInstance->incrementStaticMember(); // $MyStaticMember will now be: 2
    
    echo MyClass::$MyStaticMember; //will echo: 2
    $firstClassInstance->echoStaticMember(); //will echo: 2
    $secondInstance->echoStaticMember(); //will echo: 2
    
    SomeMethodInAFarFarAwayScript(); //will echo: 2
    

    PHPFiddle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?