-3

I need to transform to uppercase a string setted by dynamic __set constructor of my PHP class. Just like JavaScript .toUpperCase() function.

Exemple:

$myObject = new Post();
$myObject->fooVar = 'Upper Case Test';
$myObject->fooVar->toUpperCase();
echo $myObject->fooVar;

Need to output: UPPER CASE TEST

This is my actual class code:

class Post {
    private $data;

    public function __construct()
    {
        echo 'Class "'. __CLASS__. '" started!'; // constructor debug
    }

    public function __destruct()
    {
        echo 'Class "'. __CLASS__. '" destroyed.'; // constructor debug
    }


    public function __get($varName)
    {
        if (!array_key_exists($varName, $this->data))
        {
            //this attribute is not defined!
            $this->data[$varName] = 'ERROR!';
            return $this->data[$varName];
        }
        else
        {
            return $this->data[$varName];
        }
    }

    public function __set($varName, $value)
    {
        $this->data[$varName] = $value;
    }

    public function toUpper($object){
        $object = strtoupper($object);  
        return  $object;
    }
}

Is this possible?

Thanks for all,

1 Answers1

0

I don't believe there is a way to do it using the syntax in your example code. The variable you are accessing is a string and doesn't have a toUpperCase function. If you must use a function format like that, I'd say the best way I can think to do this by adding the toUpperCase function to your Post class like this.

class Post {

    ...

    public function toUpperCase($key){
        if (array_key_exists($key, $this->data) && is_string($this->data[$key])) {
            $this->data[$key] = strtoupper($key);
        }
    }
}

Then you can use it like so:

$myObject = new Post();
$myObject->fooVar = 'Upper Case Test';
$myObject->toUpperCase('fooVar');
echo $myObject->fooVar;

However, I think something like the following would be better and doesn't require the toUpperCase function.

if ($myObject->fooVar)
    $myObject->fooVar = strtoupper($myObject->fooVar);

I'd recommend modifying your __get definition to return false at the very least if the key doesn't exist (an exception might be better, but depends on how you use this class). If you are returning a string, this forces you to do a string comparison to error check which is needless extra code.

kunruh
  • 874
  • 1
  • 8
  • 17
  • Thanks for the answer. The purpose of my question is know how to use PHP OO like in JavaScript, with several inline functions changing the object's content. Example: ` var test = 'Object'; var concatText = 'in JavaScript ###'; alert(test.concat(" ", concatText).replace('###','123').toUpperCase()); ` – Michael Olem Mar 18 '17 at 16:47