【问题标题】:PHP - change class variable/function from outside the classPHP - 从类外部更改类变量/函数
【发布时间】:2011-06-24 17:26:12
【问题描述】:

我可以从类外部更改类中定义的函数或变量,但不使用全局变量吗?

这是类,包含文件#2:

class moo{
  function whatever(){
    $somestuff = "....";
    return $somestuff; // <- is it possible to change this from "include file #1"
  }
}

在主应用程序中,类是这样使用的:

include "file1.php";
include "file2.php"; // <- this is where the class above is defined

$what = $moo::whatever()
...

【问题讨论】:

  • “包含文件#1”是什么意思?
  • $somestuff 似乎是一个局部变量。你不能在$what = moo::whatever()之后改变$what的值吗?
  • “更改功能”是什么意思?
  • 你的意思是写一个“元”编程来改变一个功能吗?
  • 不确定但可能重复Can I include code into a PHP class?

标签: php class function variables


【解决方案1】:

在构造函数中将其设置为实例属性,然后让方法返回属性中的任何值。这样,您可以在任何可以获取对它们的引用的地方更改不同实例的值。

【讨论】:

    【解决方案2】:

    你问的是 Getter 和 Setter 还是 Static variables

    class moo{
    
        // Declare class variable
        public $somestuff = false;
    
        // Declare static class variable, this will be the same for all class
        // instances
        public static $myStatic = false;
    
        // Setter for class variable
        function setSomething($s)
        {
            $this->somestuff = $s;
            return true; 
        }
    
        // Getter for class variable
        function getSomething($s)
        {
            return $this->somestuff;
        }
    }
    
    moo::$myStatic = "Bar";
    
    $moo = new moo();
    $moo->setSomething("Foo");
    // This will echo "Foo";
    echo $moo->getSomething();
    
    // This will echo "Bar"
    echo moo::$myStatic;
    
    // So will this
    echo $moo::$myStatic;
    

    【讨论】:

      【解决方案3】:

      实现您的目标有多种可能性。您可以在 Class 中编写 getMethodsetMethod 来设置和获取变量。

      class moo{
      
        public $somestuff = 'abcdefg';
      
        function setSomestuff (value) {
           $this->somestuff = value;
        }
      
        function getSomestuff () {
           return $this->somestuff;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-10
        • 2014-08-02
        • 2014-10-12
        • 2019-02-04
        • 1970-01-01
        • 2019-02-19
        • 2023-04-02
        • 1970-01-01
        相关资源
        最近更新 更多