質問

I would like to know if it is possible in php5, to instantiate an object as a class variable?

Down here on my example, the variable $a would be an instance of class A. But when I work on it it does not seem to be feasible.

Could you tell me how could I make the relation-ship "Class B has a variable that is an instance of class A" ??

<?php 
class A{
    private $variable1;
    private $variable2;
}   
class B{
    private $variable3;
    private $variable4;
    private $a = new A();
}   
?>
役に立ちましたか?

解決

Initialize the assignment inside a constructor. After that make an instance of class B and you can right away call the method which is in class A.

FYI : The variable $a is made as public.


The code...

<?php
class A
{
    private $variable1;
    private $variable2;

    public function show()
    {
        echo "Hi";
    }
}

class B
{
    public $a;
    private $variable3;
    private $variable4;

    function __construct()
    {
        $this->a = new A;
    }
}

$b = new B;
$b->a->show(); // prints Hi

他のヒント

You can't instantiate objects in the class definition. However, you can use the __construct() magic method!

class A{
    private $variable1;
    private $variable2;
}   
class B{
    private $variable3;
    private $variable4;
    private $a;

    function __construct() {
        $this->a = new A();
    }
}

The method __construct() is executed while instantiating class B (new B()). So whenever a B exists, it has a variable holding an instance of class A

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top