dp926460 2011-07-01 16:18
浏览 31
已采纳

哑实验 - 在PHP中创建C#-esque属性

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条回答 默认 最新

  • douzuo0002 2011-07-05 19:45
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)