-3

I have to define the type of a property of my class say Bb as another class Attach. I tried writing it as below-

<?php

class Attach{
    var $attachmentId;

    var $displayName;

    var $hyperlinkText;

    var $content;
}

class Bb{
    var Attach $attachment;
}

But it is giving me an error -

Parse error: syntax error, unexpected 'public' (T_PUBLIC) in /home/......

What is the correct way to achieve it ?

piyush
  • 976
  • 4
  • 13
  • 28
  • The tag says PHP 5.4, yet you use PHP 4 OOP coding style? Better read the manual a bit more... – Matteo Tassinari Jul 18 '14 at 11:15
  • @MatteoTassinari , I followed the PHP5.4 manual. But I still didn't find a simple approach for my real scenario. In my real scenario, there are 30 to 40 properties of Bb class. I don't want them to pass them as an argument in Constructor. You will probably want me create setter methods and set those protected properties using setter methods. I am feeling lazy about writing those extra lines of code( setter methods). Could you suggest a lazy way of doing it? By lazy i mean writing less lines of code. – piyush Jul 18 '14 at 11:33
  • You could send the properties in as an array, but lazyness never helped good software development. – Matteo Tassinari Jul 18 '14 at 11:56

2 Answers2

2

the problem is here:

class Bb{
    var Attach $attachment;
}

remove the Attach:

class Bb{
    var $attachment;
}

you shouldn't really be using var anyway, try to start using private, public, protected etc.

Greg K
  • 434
  • 4
  • 7
1

Try using this:

<?php

class Attach{

    protected $attachmentId;

    protected $displayName;

    protected $hyperlinkText;

    protected $content;

}


class Bb{

    protected $attachment;

    public function __construct(Attach $attachment){
        $this->attachment = $attachment;
    }
}

$attachment = new Attach();
$bb = new Bb($attachment);

Note that you are using PHP 4 style OO in your example.

See the manual on OO Programming in PHP for more details.

Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
  • In my real scenario, there are 30 to 40 properties of Bb class. I don't want them to pass them as an argument in Constructor. You will probably want me create setter methods and set those protected properties using setter methods. I am feeling lazy about writing those extra lines of code( setter methods). Could you suggest a lazy way of doing it? By lazy i mean writing less lines of code. – piyush Jul 18 '14 at 11:31
  • 2
    Send the properties in as an array with specific key values? – Wayne Whitty Jul 18 '14 at 11:33