Tom
Tom

Reputation: 734

PHP How to use a property declared in another method?

I recently started with PHP Object Oriented and I cannot seem to get this done. In a method I declare a property which I want to use in another method, but I get an error: Undefined property: Database::$test.

class Database {

    public function connect() {
        $connection = 'hoi';
    }

    public function disconnect() {
        echo $this->connection;
    }

}

$db = new Database();
$db->connect();
$db->disconnect();

Again, I'm new at OOP. I tried using global with the scope of a function in mind which would make sense in a regular function, but I just get another error when I use that.

Upvotes: 1

Views: 546

Answers (2)

daiscog
daiscog

Reputation: 12077

You have declared connection as a variable, not a property. This is what you want.

class Database {

    private $connection;

    public function connect() {
        $this->connection = 'hoi';
    }

    public function disconnect() {
        echo $this->connection;
    }

}

Read the PHP.net documentation on classes and objects.

Upvotes: 7

Marc B
Marc B

Reputation: 360872

public function connect() {
    $connection = 'hoi';
}

is simply defining a local variable, not assigning as a property in the object. It should be:

    $this->connection = 'hoi';

Upvotes: 5

Related Questions