PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Tue Dec 18, 2018 7:17 am

All times are UTC - 5 hours




Post new topic Reply to topic  [ 3 posts ] 
Author Message
PostPosted: Wed Nov 19, 2014 8:47 am 
Offline
Forum Commoner

Joined: Mon Nov 17, 2014 9:03 pm
Posts: 83
This is my code:

------------------------------------------------------------
Syntax: [ Download ] [ Hide ]
  1. class ClassB { 
  2.  
  3. private $obj = new ClassA(); 
  4.  
  5. } //end of ChessBlock 


----------------------------------------------------------------

In my php IDE, Eclipse, why am I getting syntax error from using the keyword [NEW] to created a new instance object of ClassA as a private object inside ClassB?

it says, "syntax error, unexpected new"

Any help please.


Top
 Profile  
 
PostPosted: Wed Nov 19, 2014 8:54 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6424
Location: Montreal, Canada
http://php.net/manual/en/language.oop5.properties.php

Property initializations must use a constant value. For what you're trying to do, assign the value of $obj inside the constructor, either by instantiating ClassA in the constructor or, better, by injecting it into the constructor.

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Wed Nov 19, 2014 8:56 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6424
Location: Montreal, Canada
Syntax: [ Download ] [ Hide ]
<?php

class ClassB {
        private $obj;

        public function __construct() {
                $this->obj = new ClassA();
        }
}
$b = new ClassB();

// Better

class ClassC {
        protected $obj;

        public function __construct(ClassA $obj) {
                $this->obj = $obj;
        }
}
$a = new ClassA();
$c = new ClassC($a);

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 10 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group