简体   繁体   中英

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'} doesn't seem to work...

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

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. To String works like this

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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