Search code examples
phpclassscopeinstance-variablesdeclare

Declaring an instance variable in another class using PHP 5.2.17


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!


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() );
    
    ?>