Question

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!

Was it helpful?

Solution

You can new locator class in 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() );

?>

OTHER TIPS

You can't set property because it belong to object not a class. You can fix it by creating your locator in constructor

class Doc {
    private $loc;

    public function __construct() {
        $this->loc = new Locator()
    }
    public function locator() {
        return $this->loc;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top