John Smith
John Smith

Reputation: 1780

Class Initialization Error: Call to a member function on a non-object?

The model of my class is like this:

class Foo {
    private $date;
    public function set_date($date) {
        $this->date = $date;
    }

    // ANSWER: this gets executed as a constructor (case-insensitive)
    public function foo() {
        print_r($this->date->format('Y'));
    }
}

$Foo = new Foo();

I get: Fatal error: Call to a member function format() on a non-object when calling new Foo().

I have been unable to reproduce the error (the above code seems to work).

The above code is now an exact replica of the error.

Upvotes: 0

Views: 947

Answers (3)

Madbreaks
Madbreaks

Reputation: 19539

This is a syntax error:

print_r($this->Date->format('Y');
                              ^^^^  missing closing paren

Upvotes: 4

Arjan
Arjan

Reputation: 9874

Since the error occurs when you create the class instance using new Foo() I would suspect that there is a method foo() in the class. Because there is no __construct() the method foo() is considered the constructor and gets executed. This could trigger the error, either directly or through calls to other methods.

Upvotes: 2

GolezTrol
GolezTrol

Reputation: 116100

There's probably other code that is executed. The method format is called in the method b. b is not called in the code you gave, but it's probably called elsewhere, and before the date is set.

Upvotes: 2

Related Questions