简体   繁体   中英

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?

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.

This is a simple solution, just use array_map([static::class, 'escape'], $values) instead of __NAMESPACE__ :

class Cleanse
{ 
    public static function escape($values)
    {
        return is_array($values) ?
                    array_map([static::class, 'escape'], $values) :
                    htmlentities($values, ENT_QUOTES, 'UTF-8');
    }           
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM