2

I understand that PHP doesn't allow me to create a new instance of ClassB inside my ClassA, if the creation is not inside the scope of a function. Or I just don't understand...

class ClassA {

const ASD = 0;
protected $_asd = array();
//and so on

protected $_myVar = new ClassB(); // here I get *syntax error, unexpected 'new'* underlining 'new'

// functions and so on
}

Do I need some kind of constructor, or is there a way to actually create the object instance in a free way as I desire, as I am used to do in Java or C#. Or is using Singleton the only closest solution to my approach?

P.S. ClassB is located in the same package and folder as ClassA.

3
  • 1
    And where's the code for ClassB? Commented Nov 5, 2013 at 16:17
  • @sal00m - good question. I updated my post. Look at the P.S.. :) Commented Nov 5, 2013 at 16:19
  • RTFM: php.net/manual/en/language.oop5.properties.php class attributes can be intialized with constant values only. Expression results are expressly forbidden. You need to do what you want in the classA constructor. Commented Nov 5, 2013 at 16:20

2 Answers 2

4

According to the PHP docs:

declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

As such, you will need to instantiate $_myVar in your constructor:

protected $_myVar;    

public function __contruct() {
   $this->_myVar = new ClassB();
}
Sign up to request clarification or add additional context in comments.

4 Comments

So I guess this object is created at compile time and I can use it in the rest of the class simply as $_myVar->someFunctionFromClassB(), is that correct?
Yes, don't forget the this prefix, of course: $this->_myVar->someFunctionFromClassB()
@JasonMcCreary - good tip! Old habits from Java die hard... I have to get used to the PHP syntax.
You should read the docs as an introduction. Then reread them after you write some code :)
2

Yes, there is a constructor (see below)

class ClassA {

    const ASD = 0;
    protected $_asd = array();
    //and so on

    protected $_myVar; // initialization not allowed directly here

        public function __contruct() {
            $this->_myVar = new ClassB();
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.