douyonglang4845 2011-03-30 04:59
浏览 25
已采纳

从单独的函数中提取变量

If I have two public functions and I want to pull a variable from one inside of another, what is the best way to accomplish this? I know about 'global' but this method seems like it could cause me problems down the road.

Imagine I have something like this:

class myCMS {

   public function process_apples() {

   $a = $_POST['$apples'];

   }

   public function display_apples() {

   echo $a;

   }
}

How would I go about using display_apples() to report $a from process_apples()? Im new to PHP, so feel free to let me know if I am violating some best practicing for organizing my code.

  • 写回答

3条回答 默认 最新

  • doujing4555 2011-03-30 05:02
    关注

    If you have two methods in a class, and want a variable to shared between them, you should use a class property -- which is kind of a variable that's inside a class.


    Your class would then look like this :

    class myCMS {
        protected $a;   // declare the property (won't be visible from outside the class)
    
        public function process_apples() {
            $this->a = $_POST['$apples'];
        }
    
        public function display_apples() {
            echo $this->a;
        }
    }
    


    And a couple of notes :

    • You need to use $this->property_name to access a property
    • Not related, but you should generally no use $_POST from inside your class : it makes your class dependent on external global variables -- of course, up to you to determine whether it's a problem or not.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了