Is it a bad practice ?
Mbenga

Mbenga @jeremymonatte

About: Just a french web guy. Alsow, i love ❤️ Otter ❤️

Location:
Le-Puy-en-Velay, France
Joined:
Jul 8, 2020

Is it a bad practice ?

Publish Date: Oct 6 '21
3 2

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

Comments 2 total

  • Alican YILDIZ
    Alican YILDIZNov 11, 2021

    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
    • Mbenga
      MbengaNov 12, 2021

      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

Add comment