0

I'm having some real trouble with this, and I can't seem to figure out why. Please see code below. As you can see I have an array for $serverDrives set to 'C' and 'F'. I have a loop to create a new Object from a class (Drive) however when I use GetDriveLetter on the drivesArray it will always return F no matter what index I've used. I've checked that in the for loop it has both C and F, but no matter what I do I can't get it to return anything but F.

$serverDrives = ['C', 'F'];

$drivesArray = [];
for($i = 0; $i < count($serverDrives); $i++) {
    $drivesArray[$i] = new Drive($serverDrives[$i]);
}

echo $drivesArray[0]->GetDriveLetter();

Here is Drive.class.php:

<?php
class Drive {
    public $DriveLetter;

    public function Drive($driveletter) {
        global $DriveLetter;
        $DriveLetter = $driveletter;
    }

    public function GetDriveLetter() {
        global $DriveLetter;
        return $DriveLetter;
    }
}

Any ideas?

1
  • Using global for a variable is rarely a good idea. Here is leads to desaster. Commented Aug 2, 2015 at 5:38

1 Answer 1

2

Change your class code to this:

class Drive {
    public $DriveLetter;

    public function Drive($driveletter) {
        $this->DriveLetter = $driveletter;
    }

    public function GetDriveLetter() {
        return $this->DriveLetter;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

That did the trick, but I'm curious why? What's the difference between global and using this? I assume that global is literally that, the global variable that was set last in the class? Whereas this references the Object I'm currently calling?
@user2416047 I think you can answer that yourself: if you have a global variable and return the value of that in all objects of that class, why do you expect to receive different values from different objects? You always ask the value of the single, global variable.
global means make the variable thats set elsewhere available for modification in the function. $this means applicable to the class
Thanks guys! I misunderstood how global works! I'll set this as the best answer when I can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.