简体   繁体   中英

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?

Change your class code to this:

class Drive {
    public $DriveLetter;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM