Dumb experiment - creating C#-esque properties in PHP

 ̄綄美尐妖づ 提交于 2020-03-24 13:47:17

问题


I'm trying to come up with a graceful way to create C#-esque properties in PHP

Right now, I have:

class Example
{
    private $allowedProps = array('prop1', 'prop2', 'prop3');
    private $data = array();

    public function __set($propName, $propValue)
    {
        if (in_array($propName, $this->allowedProps))
        {
            // set property
        }
        else
        {
            // error
        }
    }

    public function __get($propName)
    {
        if (array_key_exists($propName, $this->data))
        {
            // get property
        }
        else
        {
            // error
        }
    }
}

In the commented out sections, for something more complex than simply writing to or retrieving from the $data array, the easiest thing to do would be to simply branch logic where necessary with an if-else or switch. That's messy, though, and runs counter to what I want. Is there a way to invoke a callback function that would have access to the $data array?


EDIT: Seems like the simplest thing to do would be:

class Example
{
    private $allowedProps = array('prop1', 'prop2', 'prop3');
    private $data = array();

    public function __set($propName, $propValue)
    {
        $propName = strtolower($propName);

        if (in_array($propName, $this->allowedProps))
        {
            $funcName = "set" . ucfirst($propName);
            $this->$funcName($propValue);
        }
        else
        {
            // error
        }
    }

    public function __get($propName)
    {
        $propName = strtolower($propName);

        if (array_key_exists($propName, $this->data))
        {
            $funcName = "get" . ucfirst($propName);
            $this->$funcName();
        }
        else
        {
            // error
        }
    }

    private function getProp1()
    {
        // do stuff, and return the value of prop1, if it exists
    }

    // ...
}

I'm not sure if having a host of private setter and getter methods is the way to go. Lambdas would probably be ideal, but they're only available in PHP 5.3+.


回答1:


Not really an answer, per se, but I figured I'd mark it as solved for now as I haven't had the time to experiment further. Of course, any additional suggestions are welcome.



来源:https://stackoverflow.com/questions/6550550/dumb-experiment-creating-c-esque-properties-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!