简体   繁体   English

如何动态设置类变量?

[英]How to set class variables dynamically?

Consider the following code: 考虑以下代码:

class Project
{
    public $ProjectID;
}    
class Work
{
    public $WorkID;
}    

public function insert($pData, $tableName)
{
//generate insert here
    $pData->{$tableName . 'ID'} = $result->getId();
}

$p = new Project();
$w = new Work();
insert($w, 'Work');
insert($p, 'Project');

echo $p . ' -- ' . $w;

Now how would I go about setting the variable in a dynamic way? 现在,我将如何以动态方式设置变量? I'm building a data layer. 我正在建立一个数据层。 The $pData->{$tableName . 'ID'} $pData->{$tableName . 'ID'} $pData->{$tableName . 'ID'} doesn't seem to work... $pData->{$tableName . 'ID'}似乎不起作用...

This is what you're looking for: 这是您要寻找的:

public function set_to_seven($p_data, $name)
{
    $name = $name . 'ID';
    $p_data->$name = 7;
}

The property name can be a variable. 属性名称可以是变量。 Just like functions: 就像函数一样:

$p = 'print_r';
$p('StackOverflow');

For future reference: if you need this statically, you're looking for variable variables, 供将来参考:如果您静态需要此功能,那么您正在寻找可变变量,

public function set_to_seven($p_data, $name)
{
    $name = $name . 'ID';
    $p_data::$$name = 7;
}

So, you want to dynamically call setters? 因此,您要动态调用设置器吗?

$y = new stdClass();
$y->prop1 = "something";

$targetProperty = "prop1";
$y->$targetProperty = "something else";
echo $y->prop1;

//Echos "something else"

That what you're looking for? 那是您要找的东西吗?

You can set public properties by accessing them just like any other definition in the class. 您可以像访问类中的任何其他定义一样通过访问公共属性来设置公共属性。

$p = new Project();
$p->ProjectID = 5;
echo $p->ProjectID; // prints 5

http://php.net/manual/en/language.oop5.visibility.php http://php.net/manual/en/language.oop5.visibility.php

This worked for me. 这对我有用。

class Project {
    public $ProjectID;
}

function setToSeven($pData, $name) {
    $pData->{$name . "ID"} = 7;
}

$p = new Project();
setToSeven($p, 'Project');

echo $p->ProjectID;

You just need to echo the variable or set up a toString function on the class to echo the class. 您只需要回显变量或在类上设置toString函数以回显该类。 To String works like this To String就像这样

class Project {
    public $ProjectID;
    public function __toString(){
        return (string)$this->ProjectID;
    }
}

function setToSeven($pData, $name) {
    $pData->{$name . "ID"} = 7;
}

$p = new Project();
setToSeven($p, 'Project');

echo $p;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM