Eugeny89
Eugeny89

Reputation: 3731

initializing class field with an object

I'm new to php so the question is dump. Take a look at the following code

class A {
    private $obj;

    public function A() {
        $this->obj = new Obj();
        //$this->obj->fff() works here;
        //still var_dump($this->obj) prints NULL here
    }

    public f() {
        //$this->obj is NULL here!!!
        //$this->obj->ff() throws an error
    }
}

UPD in f() I get Fatal error: Call to a member function ff() on a non-object in ...

how should I init $obj to see it in f()?

Thank you in advance!!

Upvotes: 0

Views: 128

Answers (2)

s.webbandit
s.webbandit

Reputation: 17000

You have an error in function name A() which s similar to class name. When you call $a = new A; actually A() method of A class is invoked. Use __construct() instead.

On my server this works fine:

<?php 

class A {

    private $obj;

    public function A() {

        $this->obj = new stdClass();

    }

    public function f() {

        var_dump($this->obj);

    }

}

$aa = new A;

$aa->f(); // Prints `object(stdClass)#2 (0) { }`

?>

Looks like you have a problem with with your Obj class. And why don't you place function in public f() { in your class definition?

Upvotes: 1

Petar Minchev
Petar Minchev

Reputation: 47373

Try the following:

public function __construct() {
     $this->obj = new Obj();
}

I think the problem is you missed function. I am not really a PHP guy but I think public function A() will work too, but the __construct is preferred.

Edit: Now you added function. I am not really sure if my answer will help you then.

Upvotes: 3

Related Questions