0

I simply want to declare an instance variable in a second class in the same file. The following example code seems okay to me, but the server results an error at the commented line:

For example:

<?php

class Locator {
    private $location = __FILE__;

    public function getLocation() {
        return $this->location;
    }
}

class Doc {
    private $loc = new Locator(); // [SYNTAX-ERROR] unexpected T_NEW

    public function locator() {
        return $this->loc;
    }
}

$doc = new Doc();
var_dump( $doc->locator() );

?>

Many thanks to everyone's help!

4

2 回答 2

1

您不能设置属性,因为它属于对象而不是类。您可以通过在构造函数中创建定位器来修复它

class Doc {
    private $loc;

    public function __construct() {
        $this->loc = new Locator()
    }
    public function locator() {
        return $this->loc;
    }
}
于 2013-07-04T08:27:03.260 回答
1

您可以在 Doc::locator() 中新建定位器类;

class Locator {
    private $location = __FILE__;

    public function getLocation() {
        return $this->location;
    }
}

class Doc {
    public function locator() {
        return new Locator();  // new locator here
    }
}

$doc = new Doc();
var_dump( $doc->locator() );

?>
于 2013-07-04T08:17:36.020 回答