2

for my new job I have to learn PHP, and so far I'm finding it quite frustrating (I'm used to desktop languages, like C#, Java, etc.).

I'm kind of teaching myself the language, and just creating little projects at a time.

Right now I have three classes:

Customer
DateOfBirth
Address

In the Customer class, I have getter and setter methods. For the setter methods, I'd like to check the type of a parameter.

For example: (pseudo):

func set_address($address)
    if $address typeof Addess then
        this->address = $address
    else then
        throw ArgumentException("Invalid parameter!");
    end
end 

I hope you get what I mean. I just want things to be right and not get used to doing stupid things.

I hope you can help! Cheers in advance!

SimonC
  • 1,547
  • 1
  • 19
  • 43
  • 2
    You were close. Instead of `typeof` it's `instanceof` (BTW: I love your attempt with the pseudo code. Makes your question clear and shows what you want to know) – Rizier123 May 21 '15 at 13:16
  • 2
    Another way to enforce type of an argument is to use type hinting in the signature: `public function set_address (Address $address) { ... }` – Kevin Nagurski May 21 '15 at 13:20
  • There is a goog example in the [php manual](http://php.net/manual/en/language.oop5.typehinting.php) hope this hepl ;) – Maraboc May 21 '15 at 13:23
  • @Rizier123 Might as well do my best and help others help me, right? :) – SimonC May 21 '15 at 13:25
  • Thanks guys, I solved it like this: if ($address instanceof Address) $this->$m_address = $address; – SimonC May 21 '15 at 13:31

0 Answers0