Php имя объекта из переменной

Как установить имя объекта из переменной?

как сделать так чтоб имя атрибута можно было установить из переменной?

Оценить 2 комментария

Petroveg

Атрибутов в переменной нет:) В DOM-элементах есть, а переменные в Javascript нужны для хранения значений.
Сформулируйте вопрос точнее.

Как написать цикл чтобы в результате получить такую структуру?

Petroveg

Да, пожалуй, напрямую никак:) По спецификации именем свойства может быть значение строки или символа.
Вариантов работы несколько (откуда берётся возраст, не знаю:).

По старинке (или для словарей)

var countName = [ 'Петя', 'Вася' ]; for (var i = 0, data = []; i < countName.length; ++i) < data.push(<>); data[data.length - 1][countName[i]] = < age: 10 >; >
for (var i = 0, data = []; i < countName.length; ++i) < data.push(set(countName[i], 10)); >function set (name, value) < var object = <>; object[name] = < age: value >; return object; >
for (var i = 0, data = []; i < countName.length; ++i) < data.push(set(countName[i], 10)); >function set (name, value) < var object = <>; Object.defineProperty(object, name, < value: < age: value >>); return object; >

Источник

Php имя объекта из переменной

It may be worth specifically noting, if variable names follow some kind of «template,» they can be referenced like this:

// Given these variables .
$nameTypes = array( «first» , «last» , «company» );
$name_first = «John» ;
$name_last = «Doe» ;
$name_company = «PHP.net» ;

// Then this loop is .
foreach( $nameTypes as $type )
print $ < "name_ $type " >. «\n» ;

// . equivalent to this print statement.
print » $name_first \n $name_last \n $name_company \n» ;
?>

This is apparent from the notes others have left, but is not explicitly stated.

In addition, it is possible to use associative array to secure name of variables available to be used within a function (or class / not tested).

This way the variable variable feature is useful to validate variables; define, output and manage only within the function that receives as parameter
an associative array :
array(‘index’=>’value’,’index’=>’value’);
index = reference to variable to be used within function
value = name of the variable to be used within function

$vars = [ ‘id’ => ‘user_id’ , ’email’ => ‘user_email’ ];

function validateVarsFunction ( $vars )

//$vars[‘id’]=34; // define allowed variables
$user_id = 21 ;
$user_email = ’email@mail.com’ ;

echo $vars [ ‘id’ ]; // prints name of variable: user_id
echo $< $vars [ 'id' ]>; // prints 21
echo ‘Email: ‘ .$< $vars [ 'email' ]>; // print email@mail.com

// we don’t have the name of the variables before declaring them inside the function
>
?>

The feature of variable variable names is welcome, but it should be avoided when possible. Modern IDE software fails to interpret such variables correctly, regular find/replace also fails. It’s a kind of magic 🙂 This may really make it hard to refactor code. Imagine you want to rename variable $username to $userName and try to find all occurrences of $username in code by checking «$userName». You may easily omit:
$a = ‘username’;
echo $$a;

If you want to use a variable value in part of the name of a variable variable (not the whole name itself), you can do like the following:

$price_for_monday = 10 ;
$price_for_tuesday = 20 ;
$price_for_wednesday = 30 ;

$price_for_today = $< 'price_for_' . $today >;
echo $price_for_today ; // will return 20
?>

PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2

class Foo public function hello () echo ‘Hello world!’ ;
>
>
$my_foo = ‘Foo’ ;
$a = new $my_foo ();
$a -> hello (); //prints ‘Hello world!’
?>

Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3

class Foo public static function hello () echo ‘Hello world!’ ;
>
>
$my_foo = ‘Foo’ ;
$my_foo :: hello (); //prints ‘Hello world!’
?>

You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: —

foreach ( $array as $key => $value )
$ $key = $value ;
>

?>

This however would be reinventing the wheel when you can simply use:

extract ( $array , EXTR_OVERWRITE );
?>

Note that this will overwrite the contents of variables that already exist.

Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: —

$array =array( «one» => «First Value» ,
«two» => «2nd Value» ,
«three» => «8»
);

extract ( $array , EXTR_PREFIX_ALL , «my_prefix_» );

?>

This would create variables: —
$my_prefix_one
$my_prefix_two
$my_prefix_three

containing: —
«First Value», «2nd Value» and «8» respectively

Another use for this feature in PHP is dynamic parsing..

Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created. In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.

Normally, you won’t need something this convolute. In this example, I needed to load an array with dynamically named objects — (yes, this has some basic Object Oriented programming, please bare with me..)

// this is only a skeletal example, of course.
$object_array = array();

// assume the $input array has tokens for parsing.
foreach ( $input_array as $key => $value ) <
// test to ensure the $value is what we need.
$obj = «obj» . $key ;
$ $obj = new Obj ( $value , $other_var );
Array_Push ( $object_array , $ $obj );
// etc..
>

?>

Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.

I haven’t fully tested the implimentation of the objects. The scope of a variable-variable’s object attributes (get all that?) is a little tough to crack. Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.

Then, we can easily pull everything back out again using a basic array function: foreach.

//.
foreach( $array as $key => $object )

echo $key . » — » . $object -> print_fcn (). »
\n» ;

?>

Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.

Источник

Как динамически писать имя свойства объекта PHP?

У меня есть свойства объекта в моем коде, которые выглядят следующим образом:

$obj ->field_name_cars[0]; $obj ->field_name_clothes[0]; 

Проблема в том, что у меня есть 100 имен полей и вам нужно написать динамическое имя свойства. В противном случае имя объекта и ключи для свойства всегда будут одинаковыми. Поэтому я попробовал:

Надеясь, что имя свойства будет динамически изменено и получить доступ к правильным значениям. Но я продолжаю получать поле неопределенного свойства $ в поле stdClass :: $;

Более или менее я пытаюсь динамически писать php до его выполнения, чтобы он мог выводить правильные значения. Мысли о том, как подойти к этому?

Обновление для PHP 7.0

PHP 7 представил изменения в отношении того, как косвенные переменные и свойства обрабатываются на уровне анализатора (подробнее см. Соответствующий RFC ). Это приближает фактическое поведение к ожидаемому и означает, что в этом случае $obj->$field[0] даст ожидаемый результат.

В случаях, когда поведение по умолчанию (теперь улучшено) нежелательно, фигурные скобки все еще можно использовать для переопределения, как показано ниже.

Оригинальный ответ

Напишите доступ следующим образом:

Этот трюк «заключить с фигурными скобками» полезен в PHP всякий раз, когда возникает неоднозначность из-за переменных переменных.

Рассмотрим исходный код $obj->$field[0] – означает ли это «доступ к свойству, имя которого задано в $field[0] », или «обращение к элементу с ключом 0 свойства, имя которого дано в $field «? Скобки позволяют вам быть явным.

Я думаю, что вы ищете нотацию переменной переменной переменной, которая при доступе к значениям из других массивов / объектов лучше всего достигается с помощью фигурного скобкового синтаксиса:

Волшебный метод __get – вы друг:

class MyClass < private $field = array(); public function __get($name) < if(isset($this->field[$name])) return $this->field[$name]; else throw new Exception("$name dow not exists"); > > 
$myobj = new MyClass(); echo $myobj->myprop; 

Объяснение: Все данные вашего поля хранятся в массиве. При доступе к $myobj->myprop это свойство явно не существует в классе. Именно здесь вызывается __get . __get ищет имя в массиве field и возвращает правильное значение.

aboulfazl, поскольку методы PHP 5.3.3 с тем же именем, что и класс, не будут рассматриваться как конструктор!

 YourClass < public $any = false; public function __construct($any = null) < $this->any = (is_null($any) ? $this->any : $any); > > 

Это работает, но не спрашивает владелец темы, Джон дает азерсе!

YourClass extends stdClass < public function YourClass() < $this->AnyProperty="any"; > > 

Теперь AnyProperty динамически объявляется.

Источник

Читайте также:  Использование gpu в python
Оцените статью