dtstnjl898781429 2013-01-21 15:08
浏览 136
已采纳

从另一个类调用变量,与范围问题

Ok I've narrowed down my problem but can't come up with a fix.

I want the first class to be able to reference variables from the second class.

class TheFirstClass{
    public function __construct(){
        include 'SecondClass.php';
        $SecondClass = new SecondClass;
        echo($SecondClass->hour);
    }
}

//in it's own file
class TheSecondClass{
    public $second;
    public $minute = 60;
    public $hour;
    public $day;

    function __construct(){ 
        $second = 1;
        $minute = ($second * 60);
        $hour = ($minute * 60);
        $day = ($hour * 24);
    } 
}

But in this situation, only the "minute" is able to be accessed from the other class. If I were to remove the "= 60", then the minute would return nothing along with the rest of the variables.

The variables within the constructor are calculated correctly, but they do not affect the variables of the same name higher in the scope. Why, and what would be the correct way to structure the code instead?

  • 写回答

2条回答 默认 最新

  • douzhi1972 2013-01-21 15:10
    关注

    Reference the properties with the $this-> prefix:

        $this->second = 1;
        $this->minute = ($this->second * 60);
        $this->hour = ($this->minute * 60);
        $this->day = ($this->hour * 24);
    

    By not using $this-> you are creating new local variables that only exist in the local scope, you aren't affecting the properties.

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

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)