第一种方式(继承)http://www.php.net/manual/en/language.oop5.inheritance.php
<?php
class A {
public $_x = 'x';
public $_y = 'y';
public $_z = 'zz';
}
class B extends A {
public function __construct() {
echo $this->_x . "__" . $this->_y . "__" . $this->_z;
}
}
$b = new B; // x__y__zz
?>
第二种方式 - 类实例化 - 属性是公共的,因此您可以从对象实例中访问它们的值,并将其分配给您的内部属性
<?php
class AA {
public $_x = 'x';
public $_y = 'y';
public $_z = 'zz';
}
class BB {
public $_x, $_y, $_z;
private $_AA;
public function __construct() {
$this->_AA = new AA();
$this->_x = $this->_AA->_x;
$this->_y = $this->_AA->_y;
$this->_z = $this->_AA->_z;
echo $this->_x . "__" . $this->_y . "__" . $this->_z;
}
}
$bb = new BB; // x__y__zz
?>
第三种方式,如果属性是私有的,如果你可以直接访问基类,你可以对 then 进行访问,所以即使它们不能被外部覆盖,它们的值也可以访问
<?php
class AAA {
private $_x = 'x';
private $_y = 'y';
private $_z = 'zz';
public function getX() {
return $this->_x;
}
public function getY() {
return $this->_y;
}
public function getZ() {
return $this->_z;
}
}
class BBB {
public $_x, $_y, $_z;
private $_AAA;
public function __construct() {
$this->_AAA = new AAA();
$this->_x = $this->_AAA->getX();
$this->_y = $this->_AAA->getY();
$this->_z = $this->_AAA->getZ();
echo $this->_x . "__" . $this->_y . "__" . $this->_z;
}
}
$bbb = new BBB; // x__y__zz
通用:)
<?php
class AAA {
private $_x = 'x';
private $_y = 'y';
private $_z = 'zz';
public function getX() {
return $this->_x;
}
public function getY() {
return $this->_y;
}
public function getZ() {
return $this->_z;
}
}
class BBB {
public $_x, $_y, $_z;
}
$AAA = new AAA();
$BBB = new BBB();
$get = 'get';
$arr_AAA = (array)$AAA;
foreach($arr_AAA as $key => $value) {
$property = explode('_', $key);
$property = ucfirst($property[1]);
$getter[] = $get.$property;
}
$i = 0;
foreach (get_object_vars($BBB) as $k=>$v) {
$get = $getter[$i];
$BBB->$k = $AAA->$get();
$i++;
}
var_dump($BBB);
/**
object(BBB)[2]
public '_x' => string 'x' (length=1)
public '_y' => string 'y' (length=1)
public '_z' => string 'zz' (length=2)
*
*/
这应该适用于即
private $_qwe = 'qwe';
public getQwe() {
return $this->_qwe;
}
它将第一个字母大写,因为它应该是 getter 的约定。当然,您可以建立自己的约定。