Search code examples
phpoopnamespacesarray-map

using namespace with array_map()


In a PHP web project, with two subfolders within the classes folder as follows:

project\classes\app

project\classes\utility

there is a class called Cleanse in the utility subfolder. Here is a copy of part of the code in that class:

namespace classes\utility;

class Cleanse
{
    # ATTRIBUTES
    protected static $_ns = __NAMESPACE__;   

    # METHODS
    public static function escape($values)
    {
        return is_array($values) ?
                    array_map(self::$_ns.'\Cleanse::escape', $values) :
                    htmlentities($values, ENT_QUOTES, 'UTF-8');
    }           
}

I am wondering if $_ns should be declared as static or not. Is there a better way to declare this attribute and if so, how can it be called from within functions of this class?


Solution

  • Maybe I'm missing something here, but why are you putting the value of the php magic static NAMESPACE into your own variable? Why not just use NAMESPACE directly?

    Otherwise, you can use private so only this class can access that variable and use it as $this->_ns, But realistically, i would just use the NAMESPACE variable itself.

    If you do decide to declare it statically, use self::_ns.