我不是PHP开发人员,所以我想知道在PHP中使用显式的getter/getter会不会更受欢迎,以一种纯粹的OOP风格,带有私有字段(我喜欢的方式):
class MyClass {
private $firstField;
private $secondField;
public function getFirstField() {
return $this->firstField;
}
public function setFirstField($x) {
$this->firstField = $x;
}
public function getSecondField() {
return $this->secondField;
}
public function setSecondField($x) {
$this->secondField = $x;
}
}
或者仅仅是公共字段:
class MyClass {
public $firstField;
public $secondField;
}
谢谢
发布于 2010-12-18 23:37:49
您可以使用php magic methods __get
和__set
。
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
发布于 2010-12-18 23:44:24
封装在任何面向对象语言中都很重要,流行程度与此无关。在动态类型语言中,比如PHP,它特别有用,因为如果不使用setter,几乎没有办法确保属性是特定类型的。
在PHP中,这是可行的:
class Foo {
public $bar; // should be an integer
}
$foo = new Foo;
$foo->bar = "string";
在Java中,它不会:
class Foo {
public int bar;
}
Foo myFoo = new Foo();
myFoo.bar = "string"; // error
使用魔术方法(__get
和__set
)也有效,但仅当访问可见性低于当前作用域可以访问的属性时才有效。如果使用不当,它很容易让您在尝试调试时感到头疼。
发布于 2012-11-06 22:23:36
class MyClass {
private $firstField;
private $secondField;
private $thirdField;
public function __get( $name ) {
if( method_exists( $this , $method = ( 'get' . ucfirst( $name ) ) ) )
return $this->$method();
else
throw new Exception( 'Can\'t get property ' . $name );
}
public function __set( $name , $value ) {
if( method_exists( $this , $method = ( 'set' . ucfirst( $name ) ) ) )
return $this->$method( $value );
else
throw new Exception( 'Can\'t set property ' . $name );
}
public function __isset( $name )
{
return method_exists( $this , 'get' . ucfirst( $name ) )
|| method_exists( $this , 'set' . ucfirst( $name ) );
}
public function getFirstField() {
return $this->firstField;
}
protected function setFirstField($x) {
$this->firstField = $x;
}
private function getSecondField() {
return $this->secondField;
}
}
$obj = new MyClass();
echo $obj->firstField; // works
$obj->firstField = 'value'; // works
echo $obj->getFirstField(); // works
$obj->setFirstField( 'value' ); // not works, method is protected
echo $obj->secondField; // works
echo $obj->getSecondField(); // not works, method is private
$obj->secondField = 'value'; // not works, setter not exists
echo $obj->thirdField; // not works, property not exists
isset( $obj->firstField ); // returns true
isset( $obj->secondField ); // returns true
isset( $obj->thirdField ); // returns false
准备好的!
https://stackoverflow.com/questions/4478661
复制相似问题