Mark Purnell
Mark Purnell

Reputation: 191

Calling a variable from another class, issues with scope

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?

Upvotes: 1

Views: 53

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

That variables you are using are used just inside of the __construct function. You have to use the object variables to see them in other class

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

Later edit: Note that you don't have to use include function inside the constructor of the second class. You can have something like this:

<?php
  include('path/to/my_first_class.class.php');
  include('path/to/my_second_class.class.php');

  $myFirstObject = new my_first_class();
  $mySecondObject = new my_second_class();

?>

Upvotes: 2

MrCode
MrCode

Reputation: 64526

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.

Upvotes: 5

Related Questions