user2416047
user2416047

Reputation: 100

PHP Function Returning Incorrect Value

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?

Upvotes: 0

Views: 111

Answers (1)

Mike -- No longer here
Mike -- No longer here

Reputation: 2092

Change your class code to this:

class Drive {
    public $DriveLetter;

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

    public function GetDriveLetter() {
        return $this->DriveLetter;
    }
}

Upvotes: 2

Related Questions