0

考虑以下代码:

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;

现在我将如何以动态方式设置变量?我正在构建一个数据层。$pData->{$tableName . 'ID'}好像没用...

4

4 回答 4

2

这就是你要找的:

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

属性名称可以是变量。就像函数一样:

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

供将来参考:如果您需要这个静态,您正在寻找变量变量,

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

于 2013-05-20T18:49:25.667 回答
2

那么,您想动态调用设置器吗?

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

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

//Echos "something else"

那就是你要找的东西?

于 2013-05-20T18:50:16.260 回答
1

您可以通过访问它们来设置公共属性,就像类中的任何其他定义一样。

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

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

于 2013-05-20T18:42:06.283 回答
0

这对我有用。

class Project {
    public $ProjectID;
}

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

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

echo $p->ProjectID;

您只需要回显变量或在类上设置一个 toString 函数即可回显该类。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;
于 2013-05-20T18:54:58.143 回答