Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

How to improve:

class gotClass {
    protected $field1;
    protected $Field2;
    protected $field3;
    (...)

    function __construct($arg1, $arg2, $arg3, $arg4) {
        $this->field1 = $arg1;
        $this->field2 = $arg2;
        $this->field3 = $arg3;
        (...)
    }
}

to something nice and compact like

function __construct($args) {
    $className = get_called_class();
    $classAttributes = get_class_vars($className);
    foreach ($args as $arg -> $value)
        if (array_key_exists($arg, $classAttributes))
            $this->$arg = $value;
}

I can't get it work, I don't know the right functions to use. Did I mention I'm new to PHP? Your help is much much appreciated.

share|improve this question
1  
What are you trying to achieve in words? – FractalizeR Apr 9 '11 at 20:55
trying to write a constructor that will set all the class fields without me having to hardcode the fieldnames. – Lou Bandy Apr 9 '11 at 21:10
The problem with what you're working towards, even if it does what you intend, is that this requires you to know the names of the protected fields when you construct. – jon_darkstar Apr 9 '11 at 21:46
That's what the get_class_vars() call is for – Lou Bandy Apr 10 '11 at 11:10
@Lou It returns all the fields visible from current context, not only protected ones. – FractalizeR Apr 10 '11 at 12:59
show 5 more comments

2 Answers

up vote 1 down vote accepted

What about something like:

function __construct(array $args) {
    foreach($args as $argName => $argValue) {
        if(!property_exists($this, $argName)) {
            throw new Exception("Attempt to set nonexistent property $argName!");
        }
        $this->$argName = $argValue;
    }
}

UPDATE:

And afterwards you can construct your object like this:

$myObj = new MyObject(array(
                            'field1' => 1111, 
                            'field2' => "Test string"
                     ));
share|improve this answer

I would encourage you to work on your problem without using PHP's object oriented features.

This will allow you to focus more clearly on the problem at hand and remove the need for almost all of the code that you posted.

share|improve this answer
That's the first time someone has told me not to focus on OOP. I get your point though, this exercise is a bit theoretical. Thanks – Lou Bandy Apr 12 '11 at 8:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.