dongmou3615 2011-03-01 11:23
浏览 21
已采纳

继承和OOP php中的一些属性除外?

Inheritance and except some attribute in OOP php?

I HAVE CLASS A

class A{
    var a;
    var b;
    var c;
    var d;

    function todo1()
      {
            //more code here 
      }
     function todo2()
      {
             //more code here 
      }
     function todo_with_var_c()
      {
             //more code here 
      }

    }

$A_ = new A;

I want get a new object $B the same object of A but except var c todo_with_var_c

So I tried with inheritance in php

class B extends A{

     //TODO
}

$B_ = new $B;//$B_ will the same object  $A_ but except `var c`
and and `todo_with_var_c`

How Can I do it? thanks!

  • 写回答

3条回答 默认 最新

  • douqi3195 2011-03-01 11:30
    关注

    Think about the word extends for a second. It implies the child class is an extension of the parent. Think: more than or special case or "B is an A with added responsibility". This means, you can add stuff, but you should not remove anything. If B is supposed to have less properties, B should be the parent and A the extension, e.g. the other way round.

    If you want to hide properties and/or methods in a subclass, use visibility.

    class A
    {
        protected $a;
        protected $b;
        private $c;
        protected $d;
    
        public function todo1() { … }
        public function todo2() { … }
        private function todo_with_var_c() { … }
    }
    

    Note that I made the properties protected, while in your code they are public because var is old PHP4 syntax (which you should no longer use) when there was no visibility. Properties should not be public though, but accessed through accessors methods (though opinions on that vary).

    Further learning resources:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?