John Davidson

php extended class in namespace refactor

0 comments
Message:


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.



My Answer:
To achieve the desired behavior, you can use the `use` keyword to import the classes from the global namespace into your current namespace. Here's how you can refactor your code:

php
namespace Classes{
use Basic\Defense;
use Basic\Attack;
use Basic;

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


In this code snippet, we are importing the `Defense` and `Attack` classes from the `Basic` namespace into the `Classes` namespace. This way, you can use these classes without specifying the full namespace path every time.

Rate this post

4 of 5 based on 9114 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us