php类中方法的作用域使用范围

原文链接:php类中方法的作用域使用范围

1.php类中方法的使用范围
类的方法中,控制使用范围常用的关键字有public,protected,private。
a.类方法中public的作用域作用范围
public【公共方法】 :全局可用,不仅是本类,其子类,创建的对象都可以使用,甚至子类的子类由于继承关系,也可以使用.
看个小例子,代码如下:

<?php
class Common{
    public function output(){
        return 'abc';
    }
}
class MyClass extends Common{
    public function myoutput($input='a'){
        echo '你输入了'.$input;
    }
}
$MyClass = new MyClass();
$res = $MyClass->output();
echo $res;


注:类MyClass继承了类Common,当类Common中的方法设置的作用域为public时,就可以在子类MyClass中访问。因为public的作用域是全局的,从运行结果来看,可以在子类中访问。
b.类方法中protected的作用域作用范围
protected【受保护方法】:本类和其子类使用,如果子类继承父类的话。但它和public的区别是什么呢?
区别是:public外部可以调用,而protected外部不可以调用。看个小例子,代码如下:

<?php
class Father{
    public function output(){
        return 'abc';
    }
    protected function output2(){
        return 'abc2';
    }
}
$father = new Father();
$res = $father->output();
echo $res;
echo '<hr>';
$res = $father->output2();
echo $res;
echo '<hr>';


注:从运行结果也说明了,public方法可以在外部调用,而protected方法不可以在外部调用。上述所说的在继承的子类中可以调用,指的也是在子类内部调用,在外部调用不了,如下:

<?php
class Father{
    public function output(){
        return 'abc';
    }
    protected function output2(){
        return 'abc2';
    }
}
class Child extends Father{
    public function myoutput(){
        $res = $this->output2();
        echo $res;
    }
}
$child = new Child();
$res = $child->output();
echo $res;
echo '<hr>';
$res = $child->myoutput();
echo $res;
echo '<hr>';
$res = $child->output2();
echo $res;
echo '<hr>';


注:从结果来看,在类child中,由于继承了father类,在myoutput方法中可以调用父类中受保护方法output2,但在外部,直接调用受保护的方法output2是不允许的。
c.类方法中private的作用域作用范围
private【私有方法】 : 从字面意思理解,即然是私有的,只能在本类使用,实际上也是这个意思,仅限本类,在子类中不能使用。看个小例子,如下: 

<?php
class Father{
    public function output(){
        return 'abc';
    }
    private function output2(){
        return 'abc2';
    }
}
class Child extends Father{
    public function myoutput(){
        $res = $this->output2();
        echo $res;
    }
}
$child = new Child();
$res = $child->output();
echo $res;
echo '<hr>';
$res = $child->myoutput();
echo $res;


注:从运行结果来看,在子类的内部也不能调用,所以private作用的方法只能在本类中调用。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值