DEV Community

Cover image for Is it a bad practice ?
Mbenga
Mbenga

Posted on

Is it a bad practice ?

Is it a bad pratice to do that :

<?php
class Foo
{
    public $propertie_Excplicitly_Defined;

    public function __construct()
    {
        $this->propertie_Excplicitly_Defined = "Hello";

}

$bar = new Foo();
$bar->propertie_Not_Excplicitly_Defined = "World";

Enter fullscreen mode Exit fullscreen mode

And if it's, why?

I have to pass a new variable to an object whose structure I cannot modify, and I didn't find a better way to do it. So is it bad or is it ok ? And if it's bad, do you have an idea about how i should do ?

Thanks a lot

Top comments (2)

Collapse
 
anotherglitchinthematrix profile image
Alican YILDIZ • Edited

I don't think so, it's a feature of the language. But I think it would be better to extend the class that you want to alter, this would be the cleanest and most flexible way to do that, since MyFoo extending the Foo class and sharing the same underlying structure.

<?php

class MyFoo extends Foo
{
    public $propertie_Not_Excplicitly_Defined;

    public function __construct(...$args)
    {
        $this->propertie_Not_Excplicitly_Defined = "World";
        parent::__construct(...$args)
    }
...
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jeremymonatte profile image
Mbenga

yes I agree with the extend solution, but I am in a particular case where I cannot really use it
So i think about this walkaround, but I didn't really know if it's ok or really bad