我們都知道,類的私有屬性在類外部是不可訪問的,包括子類中也是不可訪問的。比如如下**:
但某些情況下我們需要訪問類的私有屬性,有下面這麼幾種方法可以實現:<?php
class example1 $
r = function(example1 $
e); $
a = new example1();
var_dump($
r($a));
//執行結果:fatal error: cannot access private property example1::$_prop
?>
1.利用反射
2.利用closure::bind()<?php
class example1 $
r = function(example1 $
e); $
a = new example1();
$rfp = new reflectionproperty('example1','_prop');
$rfp->setaccessible(true);
var_dump($
rfp->getvalue($
a));
//結果輸出:string 'test' (length=4)
?>
此方法是php 5.4.0中新增的。
另外,我們也可以用引用的方式來訪問,這樣我們就可以修改類的私有屬性:<?php
class example1 $
r = function(example1 $
e); $
a = new example1();
$r = closure::bind($
r,null,$
a);
var_dump($
r($a));
//結果輸出:string 'test' (length=4)
?>
<?php
class example1 $
a = new example1();
$r = closure::bind(function & (example1 $
e) , null, $
a); $
cake = & $
r($a);
$cake = 'lie';
var_dump($
r($a));
//結果輸出:string 'lie' (length=3)
據此,我們可以封裝乙個函式來讀取/設定類的私有屬性:
closure::bind()還有乙個很有用之處,我們可以利用這一特性來給乙個類動態的新增方法。官方文件中給了這麼乙個例子:<?php
$reader = function & ($
object, $
property) , $
object, $
object)->__invoke();
return
$value;
}; ?>
<?php
trait metatrait
$this->methods[$
methodname] = closure::bind($
methodcallable, $
this, get_class());
} public
function __call($
methodname, array
$args)
throw runtimeexception('there is no method with the given name to call');
} }
class hackthursday $
test = new hackthursday();
$test->addmethod("addedmethod",function());
echo
$test->addedmethod();
//結果輸出:我是被動態新增進來的方法
?>
python的類訪問控制 私有屬性
一 訪問控制私有屬性 class person def init self,name,age 19 self.name name self.age age def growup self,i 1 if i 0 and i 150 self.age 1p1 person tom p1.growup 2...
類的私有屬性
前面帶有兩下劃線代表是私有屬性,能在類的內部呼叫,不能在類的外部呼叫,示例 class money self 50 all 300 def gives self print 給錢 self.self def givea self print 給錢 self.all a money a.gives a...
外部訪問C 類的私有方法和私有變數
我們知道,c 類私有方法和變數是不允許通過類例項直接訪問的,這樣子的操作會導致編譯報錯。但有沒有方法訪問到呢?有的。首先,我們需要知道c 和c語言本質上是沒有什麼區別的,c 只是語法層面上對c語言的封裝。所有c函式,只要有宣告和定義,那就可以使用,不存在public和private的區分。c 的pu...