我正在使用 PHP OOP 学习曲线
这是我的代码
文件1.php
class A
{
public $id;
public $oop;
function __construct(){
$this->time=time();
}
}
$a = new A();
我试图从另一个文件中的 B 类访问变量 id
,代码如下。
文件2.php
include('file1.php');
class B
{
function store(){
global $a; //question updated**
$x = 1;
$y = 1;
if($x == $y){
$a->id = $y; // I am setting a value for variable id.
}
}
}
$b = new B();
现在我想访问我的索引.php文件中的变量id
,如下所示。
索引.php
require_once('file2.php');
$b->store(); // Store function executed ** question updated
echo $a->id;
上面的代码没有给我任何错误,问题是我为$id
设置的值没有回显。
我还参考了这里的一些答案,这些答案几乎相似
从类中的另一个函数调用变量
如何将变量从一个类函数调用到另一个类函数
但没有解决我的问题。
请指导我在这里实现我的目标。
谢谢。
<?php
class A
{
public $foo = 'bar';
}
class B
{
public function mutateA(A $a)
{
$a->foo = 'qux';
}
}
$a = new A;
echo $a->foo;
$b = new B;
$b->mutateA($a);
echo $a->foo;
// Outputs barqux
请检查
以下代码。
file2.php - 我想你忘了调用存储方法。
class B
{
function store($a) //note the object passed
{
$x = 1;
$y = 1;
if($x == $y)
{
$a->id = $y; // I am setting a value for variable id.
}
}
}
$b = new B();
$b->store($a); //You forgot to call store method