Skip to content
Advertisement

php extended class in namespace refactor

I have made a class inside a namespace which is working perfectly fine but I think the code can be better. Right now I have to use a ‘/’ for every object inside the class which is not the best thing to do I assume.

 namespace Classes{
    use Basic

    class Enemy extends Basic{
      // Constructor
      public function __construct(){
        parent::__construct("Enemy",  new Defense("Block", ""), 60, [new Attack("Punch", 50));
      }
    }

}

Is it possible to do something like this? So I dont have to use a ‘/’ for every object but just for the class itself.

 namespace Classes{
    use Basic

    class Enemy extends Basic{
      // Constructor
      public function __construct(){
        parent::__construct("Enemy",  new Defense("Block", ""), 60, [new Attack("Punch", 50));
      }
    }
  }

I tried to do some research on Google however the only thing I can find is: https://www.w3schools.com/php/php_namespaces.asp and here is not explained how to do such thing.

Advertisement

Answer

My prefered way is this:

<?php

namespace Classes;

use Basic;
use Defense;
use Attack;

class Enemy extends Basic
{
    const WHAT_IS_THIS_NUMBER = 60;
    const ALSO_THIS_NUMBER = 50;

    public function __construct()
    {
        parent::__construct(
            "Enemy",
            new Defense("Block", ""),
            self::WHAT_IS_THIS_NUMBER,
            new Attack("Punch", self::ALSO_THIS_NUMBER)
        );
    }
}

As usual, w3school had provided ugly and oldscholl code.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement