2012-02-13 50 views
0

我正在为其中一个系统准备API方法。 Api将可用于少数语言,但第一版将针对php发布。我想知道什么命名约定应该使用访问器方法。我希望每种语言的API接口都非常相似,甚至相同。我读了一些用PHP库,发现两种命名convetion:php中的访问器方法的命名约定

1)公共存取作为集*()和get *()方法

class MyClass { 
    private $data; 
    public function getData() { 
    ... 
    } 

    public function setData($value) { 
    ... 
    } 
} 

2)退出设置/ get前缀

class MyClass { 
    private $data; 
    public function data($value = null) { 
    if (!empty($value) && is_array($value)) { 
     $data = $value; 
    } 
    return $data; 
    } 
} 

我不是php程序员,我有java和c/C++的经验,所以我想问一下有关PHP的建议。特别是对于PHP程序员来说,更可读,清晰和易于理解。

我想阅读评论和sugestions。

一切顺利。

ps。如果话题是重复的,我很抱歉,想请教我指出原来的话题。

+1

代码nr2中会发生什么?你可以使用__set和__get魔术函数,如果php 5.3是一个选项。 – busypeoples 2012-02-13 20:15:11

+0

你的第二种方法不会做任何事情,它会做,但它会返回你发送给它的值,如果该值是一个数组失败,它将返回NULL。 – CBusBus 2012-02-13 20:22:02

回答

1

试试这个作为一个起点。你需要做更多,但是这应该给你一个想法,如果这是一个选项,如何使用__get和__set。

class MyClass { 

    protected $data = array(); 
    protected $acceptedKeys = array('name', 'job', 'sport'); 

    public function __get($key) { 
    if(isset($key) && array_key_exists($key, $this->data)) { 
     return $this->data[$key]; 
    } else { 
     throw new Exception("can not find {$key}"); 
    } 
    } 

    public function __set($key,$val) { 
    if(in_array($key, $this->acceptedKeys)) { 
     $this->data[$key] = $val; 
    } else { 
     throw new Exception('we will need a key value pair'); 
    } 
    } 
} 

try { 
    $myClass = new MyClass(); 
    $myClass->job = 'sports'; 
    $myClass->name = 'test'; 
    print $myClass->job . "\n"; 
    print $myClass->name; 
} catch(Exception $e) { 
    print "error : " . $e->getMessage(); 
} 
+0

为什么你这样对我们,PHP ?!编写简单访问器的很多代码都是实际语言设计无法实现的证明。 – lkraider 2012-03-20 15:35:13

3

我几乎从来没有注意到您使用的第二个建议。
但我见过第一个经常使用的。

因此,在这种情况下,我会选择第一个。

+0

+1简洁是机智的灵魂。 – rdlowrey 2012-02-13 20:14:46