开发者

Why is this php function call failing?

I am attempting to use the following PHP class:

<?php 

class Service {

    public $code, $description;

    public static $services = array(
        "A"         =>      "Shipping",
        "B"     =>      "Manufacturing",
        "C"         =>      "Legal",
        "D"         =>      "Accounts Receivable",
        "E"         =>      "Human Resources",
        "F"         =>      "Security",
        "G"         =>      "Executive",
        "H"         =>      "IT"
    );

    public function _construct( $c, $d) {
        $this->code = $c;
        $this->description = $d;
    }

    public static function getDescription( $c ){
        return $services[$c];
    }

    public static function generateServiceList() {开发者_如何学Python

        $service_list[] = array();

        foreach ($services as $k => $v ){
            $service_list[] = new Service( $k, $v );
        }

        return $service_list;

    }

}

?>

...in the following way:

<?php
    $services = Service::generateServiceList();
?>

...but getting the following error:

Warning: Invalid argument supplied for foreach() in /classes/service.php on line 31

Any idea why? Is this some kind of an access issue? Thanks.


$services is undefined. Did yu mean self::$services ?


$services variable is declared outside the function. When using classes, you have to access it by using $this keyword like that:

...
foreach ($this->services as $k => $v ){
...

Later edit: for static variables, use self::$services instead of $this->services.


foreach ($services as $k => $v ){
            $service_list[] = new Service( $k, $v );
        }

to

foreach ($this->services as $k => $v ){
            $service_list[] = new Service( $k, $v );
        }

you want to refer to $services of the Class and not the local $services of the function.


I can't test it right now, but my gut feeling is to move $service is not being instantiated. I tend to use in this case a method for init variables. In this case you could create another method that would make

$services = array(
        "A"         =>      "Shipping",
        "B"     =>      "Manufacturing",
        "C"         =>      "Legal",
        "D"         =>      "Accounts Receivable",
        "E"         =>      "Human Resources",
        "F"         =>      "Security",
        "G"         =>      "Executive",
        "H"         =>      "IT"

Instantiation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜