0

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 pizza\land;
function turn_oven_on(){}

And you can access that function with pizza\land\hello()

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 pizza\land;
namespaced $ingredients = array('pepperoni', 'garlic');

Then access it with $pizza\land\ingredients.

Other parts in the same runtime can do:

namespace pasta\land;
namespaced $ingredients = array('tomato', 'mozzarella');

Then access it with $pasta\land\ingredients.

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...

Álvaro Franz
  • 699
  • 9
  • 26
  • 1
    Does this answer your question? [Can PHP namespaces contain variables?](https://stackoverflow.com/questions/5287315/can-php-namespaces-contain-variables) – str1ng Nov 06 '22 at 12:05
  • @str1ng Nope. That question (which I already saw) has nothing to do with my question. Did you read it or just saw the title? Thanks! – Álvaro Franz Nov 06 '22 at 12:10
  • you can use constants if that answers your question – Breezer Nov 06 '22 at 12:13
  • @Breezer a CONSTANT is not variable, and it's not namespaced, it's global. But thanks! :) – Álvaro Franz Nov 06 '22 at 12:15
  • Just to be clear, these “namespaced variables” would be globally available, too, right? You are just considering “global” to be the “empty” or “root” namespace – Chris Haas Nov 06 '22 at 12:16
  • @ChrisHaas Thanks. Well, they will be globally available as long as you `use pizza\land` before in that file. The same way any namespaced function is available only if you use the namespace. If you don't use the namespace, they are supposed to be undefined unless something else defines them globally. – Álvaro Franz Nov 06 '22 at 12:17
  • @ÁlvaroFranz Yes, I read your question twice actually, seems like I am not able to understand what are you trying to achieve or I am not able to clarify for myself what are you exactly trying to ask here... – str1ng Nov 06 '22 at 12:20
  • 1
    @str1ng Well. That question you linked is asking if you can use a variable for the namespace name itself. Or at least that is what it looks like from the answers. Also, it's over 10 years old and PHP has changed. But yeah, I am talking about something else. Having a variable live in a namespace and only be accessible within that namespace. Thanks for the attention. – Álvaro Franz Nov 06 '22 at 12:21
  • 3
    [The manual](https://www.php.net/manual/en/language.namespaces.rationale.php) said clearly: "PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants.". So variable is not grouped, if you need one, you can simply define a static class variable. – shingo Nov 06 '22 at 12:25
  • 2
    My _guess_ is that variables not bound to a context (function, class) are considered not a good idea, especially within the OOP community. Yes, WordPress has a lot of variables that are global, both explicitly and implicitly, but I think the PHP community would recommend that WordPress changes, not PHP. These are just my guesses, not my opinions. – Chris Haas Nov 06 '22 at 12:28
  • @shingo Exactly what I was going to say, but a little bit in other words. This is variable scope. In the same way, classes can be namespaced to give it scope. – str1ng Nov 06 '22 at 12:28
  • @shingo A static property cannot be edited. It's hence not a variable per se, more like a constant. – Álvaro Franz Nov 06 '22 at 12:29
  • 3
    No, A static property can be changed like a normal variable. – shingo Nov 06 '22 at 12:38
  • @shingo Oh. Now I learned something new, thanks. – Álvaro Franz Nov 06 '22 at 12:46
  • @ÁlvaroFranz Static variable are not associated to any particular instance/object of a class. Hence you modify the variable with Parent Class reference or Child Class reference, the same copy gets modified. Therefore apart from understanding Public Static as Global, understand it as not associated to any particular instance, hence with any class hierarchy reference you update a static variable , same memory location gets updated. – str1ng Nov 06 '22 at 12:47
  • @str1ng Thanks for helping and not being rude at my ignorance. Will research more on this topic now. It's what I was looking for. – Álvaro Franz Nov 06 '22 at 12:49

2 Answers2

1

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:

<?php
namespace Math;

function add($a, $b) {
    return $a + $b;
}
const PI = 3.14;

class Geometry {
    static function getCircleArea($radius) {
        return PI * $radius ** 2;
    }
}
  1. First, we declare the namespace. (So, all the classes, interfaces, constants and function below it will be items of that namespace)
  2. Then, we declared a normal function.
  3. Then, a class constant.
  4. Then, a class.

Now let's access to theseMath namespace's items from another file(functions, constants, and classes).

<?php
// includes the Math.php file
// It's like you had all the code of Math.php written here
include_once 'Math.php';

echo Math\add(2,3); // 5
echo Math\PI; // 3.14
echo Math\Geometry::getCircleArea(10); // 314.15
str1ng
  • 485
  • 3
  • 14
  • Well, sorry to hear that this is not what you were looking for (exactly). I assume that singleton as a design pattern is way to go in this case. Regarding to adding two functions it was used just for an demonstration; as you can see there's also an `constant` below `function add` -> but it's under the `namespace Math`, even if you've deleted those two function by doing `echo Math\PI` you'd still get the value of that constant. – str1ng Nov 06 '22 at 12:57
  • Hey, thanks again. I tried to edit this to make it use a static property specifically. But it didn't allow me to edit. So I just posted another answer. But seriously, thanks for helping. If you want, you can edit this answer, and make it more specific instead of adding methods and constants. And I will accept this one and delete the one I posted :) – Álvaro Franz Nov 06 '22 at 12:59
0

Thanks to @shingo's comment under the question, this is how I now learned that this can be achieved.

// Namespace
namespace whatever;

// Class with static property
class StaticStuff {
    static string $variable = 'Hey';
}

// Access it
echo StaticStuff::$variable; // Hey

// Edit it
StaticStuff::$variable = 'Miau!';

// Access it again
echo StaticStuff::$variable; // Miau!

Specifically:

  • Define a class
  • With a static property
  • Inside a namespace
Álvaro Franz
  • 699
  • 9
  • 26