4

I have the following class,e.g.

class A{
 public var1;
 public var2;
}

now, I want to create an object of this class, and I do the following:

$a = new A();
$a->var1 = 123;
$a->var2 = 987;

Is there a more better way to do this, since at times there can be even 20 such variables inside the class. I am just looking for compacting the code, and a constructor is not being used for this class. The values for variables are not static (that is why no static keyword is used)

I am looking more for this kind of assignment we do for arrays:

$arr = array(
'var1' => 123,
'var2' => 987
);

Furthermore, how will I go around avoiding NullPointerException (which sometimes comes up when I try to send this object to a .Net enabled web service) - This is optional though, as I can atlst relate this to null variables inside the class, but not exactly sure how to overcome this error.

3 Answers 3

1

Well the constructor could accept an array of parameters containing the values for these class variables which you set to the class variables inside the constructor. To avoid a null, just assign every class variable you declare to some basic value such as empty string, any value that you don't care about.

Sign up to request clarification or add additional context in comments.

2 Comments

hmm... but I can not add constructors to the classes.. I have around 100 such classes with most classes having around 5+ variables. Thanks for the null value issue - I was thinking along the same lines.
Extend the classes and then override their constructor? Is that possible? Or add a setParams method of some sort so you can pass them in bulk after creation.
0

Is there a better way to assign values to properties of a class? Well, there are multiple ways, but one is not necessarily better than the other, and they are all going to involve a similar amount of code to accomplish.

Can't answer your .NET question; I'm not familiar with it.

2 Comments

I have provided an example of what I am looking for. Any clues, please?
hmm not exactly what I am looking for, but yeah.. that does led me to create a function which will help me through this... jsbin.com/anapo3/2/edit
0

You can use PHP8's Constructor Property Promotion:

class A
{
    public function __construct(
        public $var1,
        public $var2,
        // Maybe more variables here
    ) {}
}

Cool enough. You create a class with its properties, and at the same time you initialize them in the constructor.

For more information, see the related RFC.

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.