I want to know if there is a way to namespace values, in a similar way that we namespace functions in PHP.
You can have:
namespace pizzaland;
function turn_oven_on(){}
And you can access that function with pizzalandhello()
I wonder if there is a way to do something similar for values.
This is not correct, I am just illustrating what I mean:
namespace pizzaland;
namespaced $ingredients = array('pepperoni', 'garlic');
Then access it with $pizzalandingredients
.
Other parts in the same runtime can do:
namespace pastaland;
namespaced $ingredients = array('tomato', 'mozzarella');
Then access it with $pastalandingredients
.
Of course that doesn’t work, but it serves as an example of what I mean.
I know there is the obvious way, which would be to use the Singleton pattern where the constructor sets the value of a public property for the singleton instance (the one and only one instance of the class).
I dislike this setup, and in that case I prefer to go the killer route and just do global $pseudonamespaced_pizza_land_ingredients
.
I wonder, is there anything else I can do to achieve this setup using the latest version of PHP (now 8.1)?
Why?
To have the same effect you have with global
but at the same time avoid collision.
Well, let’s say I am working with some procedural code and I need a value that can be accessed across multiple functions.
So I want to use that value within the realms of that bunch of functions.
I do not want to wrap all those functions into one Class and then use a property for that class, because in that case I just prefer the Singleton or the global.
Also, if not possible. Why not?
I cannot believe that this hasn’t been mentioned before as something to consider for integration into PHP. So, there must be a reason for this not being possible, if it isn’t. It would be a cool solution for all those codebases that are mostly procedural and use global
way too often… ehem… WordPress…
2
Answers
Thanks to @shingo's comment under the question, this is how I now learned that this can be achieved.
Specifically:
I think this could be a good answer for this question as the goal is to have variable live inside of the namespace, and that OP has overcomplicated the question for no reason.
Assuming that you have a variable named $number in the global scope of a PHP script. Inside a function, we have another variable with the same name $number, and we assign and change values of it within the function. But, the global variable remains unchanged. This is variable scope. In the same way, classes can be namespaced to give it scope.
Consider having a following code:
Now let’s access to theseMath namespace’s items from another file(functions, constants, and classes).