【问题标题】:Why is it possible to set a private member on an object instance, of the same class within an object?为什么可以在对象实例的同一类中设置私有成员?
【发布时间】:2018-12-02 21:55:00
【问题描述】:

谁能解释为什么我可以在TestFoo::getFooInstance() 中设置私人成员$bar

TestFoo::getFoo2Instance() 然而返回一个致命错误。

我一直认为私有成员应该只能从同一个对象实例而不是同一个对象类访问?

<?php

class TestFoo  {

    private $bar;

    public static function getFooInstance()
    {
        $instance = new TestFoo();
        $instance->bar = "To bar or not to bar";
        return $instance;
    }

    public static function getFoo2Instance()
    {
        $instance = new TestFoo2();
        $instance->bar = "To bar or not to bar";
        return $instance;
    }

    public function getBar()
    {
        return $this->bar;
    }
}

class TestFoo2 {
    private $bar;
    public function getBar()
    {
        return $this->bar;
    }
}

$testFoo = TestFoo::getFooInstance();
echo $testFoo->getBar();

// returns PHP fatal error
//$testFoo2 = TestFoo::getFoo2Instance();
//echo $testFoo2->getBar();
?>

【问题讨论】:

  • 我一直对同样的事情感到困惑,但似乎需要这样才能在类中有不同的实例,或者实现单例

标签: php


【解决方案1】:

protectedprivate 属性背后的想法是,一个类希望对外部代码隐藏这些属性。不是作为安全措施,而是因为这些属性仅供类内部使用,不应该是其他代码的公共接口。 public 的任何内容都可以被其他代码使用,并且应该保持不变以防止其他代码被破坏。 privateprotected 属性和方法只能由类本身使用,因此如果您需要重构或更改它们,则可以保证将更改本地化到类本身,并且保证不会破坏其他任何内容。

所以允许类修改属性并调用其类型的任何对象实例的方法,因为可以信任类本身了解其自身的实现。

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 2011-02-06
    • 2011-11-11
    • 2011-08-10
    • 2012-09-03
    • 1970-01-01
    • 2014-04-02
    • 2010-11-01
    相关资源
    最近更新 更多