dongyun6229 2009-06-27 17:58
浏览 51
已采纳

C#和PHP OOP的区别

I have a general OOP question.

If I have the following classes in C#

class Parent
{
    public string val = "Parent";

    public void getValue()
    {
        Console.WriteLine(this.val);
    }
}

class Child:Parent
{
    public string val = "Child";
}

Child child = new Child();
child.getValue();

The code outputs 'Parent'. As I understand it's because this points to Parent object, right?

If I do the same in PHP5:

class ParentClass {
public $val = 'parent';

    public function foo()
    {
        echo $this->val;
    }
}

class ChildClass extends ParentClass {
public $val = 'child';
}

$a = new ChildClass();
$a->foo();

The result will be 'child'.

Though if I change

public $val = 'parent'; 

to

private $val = 'parent';

then PHP will also show 'parent'. C# always return 'parent' with both public and private access modifiers.

Is there any reason for this? And which behavior is correct?

Any useful links to read will be highly appreciated!

Thank you!

  • 写回答

3条回答 默认 最新

  • doujia1904 2009-06-27 18:05
    关注

    There is no correct or incorrect behavior in your stated scenarios. The language designers did what made sense to them.

    The reason you don't get the expected behavior in c# is because GetValue is being called in the Parent class, where "this" means the parent val.

    To get the correct behavior, you would include the same method in the Child class, with the override keyword:

    public class Child
    {
        public string val = "Child";
        public override void GetValue()
        {
            Console.WriteLine(val);
        }
    }
    

    ...which would print "Child" to the console.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!