gpt4 book ai didi

PHP5面向对象: Accessing changed parent properties

转载 作者:搜寻专家 更新时间:2023-10-31 21:14:36 27 4
gpt4 key购买 nike

这是我的第一个问题,也是让我感到难过的问题。我不确定这是简单的事情,我忽略了它还是不可能的事情。

下面是我的原始代码的一个非常简化的版本。最终目标是输出如下:

1: 
2: this is a test
3: this is another test
4: this is another test

但是,对于当前状态的代码,其实际输出是这样的:

1: 
2: this is a test
3: this is another test
4:

我希望对象“B”能够在 first_function() 更改它之后访问 test_variable 的值。

当我将 test_variable 声明为静态时,它工作正常,但在实际应用程序中它不起作用,当我尝试回显 parent::test_variable 时,它​​输出“Object ID #17”等等。

class A
{
public $test_variable;

function __construct()
{
echo '1: ' . $this->test_variable . "<br />";
$this->test_variable = 'this is a test';
echo '2: ' . $this->test_variable . "<br />";
}

function first_function()
{
$this->test_variable = 'This is another test';
echo '3: ' . $this->test_variable . "<br />";
$b = new b;
$b->second_function();
}
}



class B extends A
{
function __construct()
{
/* Dont call parent construct */
}

function second_function()
{
echo '4: ' . $this->test_variable;
}
}

$a = new A;
$a->first_function();

// Outputs:
// 1:
// 2: this is a test
// 3: this is another test
// 4:

// but I want it to output
// 1:
// 2: this is a test
// 3: this is another test
// 4: this is another test

非常感谢您的回复。我非常感谢他们。

菲尔

最佳答案

在类中声明 public $test_variable; 意味着类的每个实例(对象)都有一个副本。 A 类中的 $test_variable 与 B 类中的 $test_variable 指向的内存地址不同。这样做是为了允许作用域并删除全局状态。正如您之前所说,将其声明为 static 会起作用,因为这样每个实例都会共享相同的变量。

在这种情况下,$test_variable 本质上是 B 类所需的依赖项。您可以很容易地通过构造函数注入(inject)获得该依赖项:

class A
{
public $test_variable;

function __construct()
{
echo '1: ' . $this->test_variable . "<br />";
$this->test_variable = 'this is a test';
echo '2: ' . $this->test_variable . "<br />";
}

function first_function()
{
$this->test_variable = 'This is another test';
echo '3: ' . $this->test_variable . "<br />";

// Instantiate instance passing dependency
$b = new b($this->test_variable);

$b->second_function();
}
}

class B extends A
{
function __construct($dependency)
{
// Set dependency
$this->test_variable = $dependency;
}

function second_function()
{
echo '4: ' . $this->test_variable;
}
}

$a = new A;
$a->first_function();

所以,这只是关于您可能会考虑如何处理它的想法。

关于PHP5面向对象: Accessing changed parent properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11763570/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com