如何编辑另一个类的属性并将其返回到另一个类?

时间:2018-02-17 20:50:53

标签: php

所以我的问题是:我正在创建一个带有php,html5,css等管理系统(学校项目)。

当用户登录时,我将其数据保存在类中。保存它们的全部目的是在购买完成后再使用它们,这样我就可以保存产品ID和用户ID。但每当我对DB进行查询时,我都会收到一个未定义的变量错误。

这是我的班级及其方法。一个用于保存数据,一个用于返回数据。

class profile_attributes{
    public $u_data;
    function attributes($u_data){
        $this->u_data=$u_data;
    }
    function attr_get(){
        return  $u_data;
    }
}

我最初如何发送参数

 $u_data = mysqli_fetch_assoc($result);
 $save_info = new profile_attributes()->attributes($u_data);

我如何尝试获取它们

$profile = new profile_attributes();
$loged_user = $profile->attr_get();

$user_id = $loged_user['id'];

3 个答案:

答案 0 :(得分:0)

看起来你并没有定义$ u_data。你所做的只是创建一个profile_attributes的新实例,然后尝试拉出未定义的$ u_data。

答案 1 :(得分:0)

$ u_data未定义,您必须在$ this

之前
class profile_attributes{
    public $u_data;
    function attributes($u_data){
        $this->u_data=$u_data;
    }
    function attr_get(){
        return  $this->u_data;
    }
}

您正在创建一个设置属性的实例,另一个用于访问它们,只使用一个实例:

// Use the same instance to set and get atributes
$profile = new profile_attributes();
$u_data = mysqli_fetch_assoc($result);
$save_info = $profile->attributes($u_data);

$loged_user = $profile->attr_get();
$user_id = $loged_user['id'];

答案 2 :(得分:0)

您正在为profile_attributes课程创建两个单独的实例。实例的属性和数据特定于自身,如果使用new class语法创建第二个实例,则不会共享。

以下是您正在做的事情的一个例子。请注意,实例内的数据不相同:

class Foo
{
    public $data;
}

$instance1 = new Foo();
$instance1->data = array[1, 2, 3];

$instance2 = new Foo();

var_dump($instance1, $instance2);

您需要共享您创建的第一个实例,并将数据库结果保存到您要检索这些属性的位置。