Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have an error probably because of the syntax and I cant find how to do it correctly.
This is my code
function myFunction($id = 'ID')
{
if (!$this->$id) {
// TO DO SOMETHING
}
}
I have the next error
Notice: Undefined property: Base::$ID ..... on line 278
I tried with
if (!$this->{$id}) {
but nothing
anyone know the correct syntax is. I cant find it on google neither.
You may use property_exists instead of using direct access if(!$this->$id):
function myFunction($id = 'ID')
{
if (!property_exists($this, $id)) {
// TO DO SOMETHING
}
}
If you are defining a property on your class, you should access it like such:
$this->id
not
$this->$id
I created an example how your code might work, and I kept the idea of accessing a property by a string. The first step is to have the class actually have a field named "ID". I set this field value in the constructor.
class My {
private $ID;
public function __construct($id) {
$this->ID = $id;
}
public function myFunction($id='ID'){
if(!property_exists($this, $id)){
echo "$id not found";
} else {
echo $this->$id;
}
}
}
$my = new My(4);
$my->myFunction();
Simply use
if(!$this->id) {
or
if(!$id) {
Try this method to get the output.
$this->id
or
$id
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I want to use ternary operator to assign two different values to the class variable.
I have following code sample where i am getting fatal error.
class test {
public $data = (true) ? "working" : "not working"; //Parse error: syntax error, unexpected '(' in C:\xampp\htdocs\Faltu\test.php on line 15
function __construct() {
echo $this->data;
}
}
$test = new test();
I have tried without class and it's working fine but in class I'm getting error.
Can anyone guide me how to achieve this?
Thanks in advance
You may only assign constant values when declaring properties, you cannot perform logical operations, like a ternary.
You can perform your logic in your __construct function:
class test {
public $data = NULL;
function __construct() {
$this -> data = true ? "working" : "not working";
echo $this -> data; // working
}
}
$test = new test();
From the documentation:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
it works have a look
class test {
public $data = NULL;
function __construct() {
echo $this -> data = true ? "working" : "not working"; //working
}
}
$test = new test();
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I was making a class in PHP for validation of a contact form, when I hit a problem. I eventually tracked it down to an array within the class, and wrote a test script to try to solve the problem:
<?php
class Object {
public $testArray = array(5);
function __construct() {
$testArray[] = 7;
}
function addNumber() {
$testArray[] = mt_rand(10,20);
}
function returnArray() {
return var_dump($testArray);
}
}
$object = new Object;
$object->addNumber();
echo($object->returnArray());
var_dump($object->testArray);
This outputs NULL array(1) { [0]=> int(5) }.
I am confused as to why this does not work. Eventually I would like the array to be private, but I can't find a way similar to get and set in C#. Any ideas?
Give this a go:
class Object {
public $testArray = array(5);
function __construct() {
$this->testArray[] = 7;
}
function addNumber() {
$this->testArray[] = mt_rand(10,20);
}
function returnArray() {
return var_dump($this->testArray);
}
}
You have to reference the class variable using $this - otherwise it'll try to set a variable local to the function you're in.
You can use PHP's magic __set() and __get() methods for similar functions to C# that you mentioned: PHP Overloading.
$testArray[] = mt_rand(10,20);
Should be:
$this->testArray[] = mt_rand(10,20);
$testArray is just another local variable (local to the function, no the class). If it has no value it is null. This is consistent with the output you're seeing. $object->testArray is never modified.
You have to access class variables using $this. So $testArray should be $this- >testArray.
class ab{
public static $abc = 34;
public static function asd(){
$a = "abc";
echo self::$a; //output 34;
}
}
ab::asd();
i want to find a way to point to a class static member .like the example above,how can i make this work?
If you access a static variable, the syntax is the following:
MyClass::$variable
So what you're doing lacks the indirection:
echo self::$$a; //output 34;
This works with regular variables the same way:
$variable
and with indirection:
$name = "variable";
$$name
An advice for your next question: Try to be more precise in your question. Pay attention to the following:
What you have
What it should do
What actually does
Where the error occurs if you know
This helps to give relevant answers more quickly instead of engaging in a meta-discussion to clarify your question.
I have this:
one string variable which holds the class name ($classname)
one string variable with holds the property name ($propertyname)
I want to get that property from that class, the problem is, the property is static and I don't know how to do that.
If the property weren't static, it would have been:
$classname->$propertyname;
if the property were a method, I could have used call_user_function
call_user_func(array($classname, $propertyname));
But in my case, am I just lost. I am however hoping that it is possible. With the thousands of functions that PHP has, he'd better have something for this as well. Maybe I'm missing something?
Thanks!
Edit:
for those with eval() solutions: thanks, but it is out of the question
for those with get _class _vars() solutions: thanks, but it seems it returns "the default properties of the given class" (php.net), and yes, I would like that value to be changable (even though it does help me in some of the cases)
If you are using PHP 5.3.0 or greater, you can use the following:
$classname::$$propertyname;
Unfortunately, if you are using a version lower than 5.3.0, you are stuck using eval() (get_class_vars() will not work if the value is dynamic).
$value = eval($classname.'::$'.$propertyname.';');
EDIT: I've just said get_class_vars() wouldn't work if the value is dynamic, but apparently, variable static members are part of "the default properties of a class". You could use the following wrapper:
function get_user_prop($className, $property) {
if(!class_exists($className)) return null;
if(!property_exists($className, $property)) return null;
$vars = get_class_vars($className);
return $vars[$property];
}
class Foo { static $bar = 'Fizz'; }
echo get_user_prop('Foo', 'bar'); // echoes Fizz
Foo::$bar = 'Buzz';
echo get_user_prop('Foo', 'bar'); // echoes Buzz
Unfortunately, if you want to set the value of the variable, you will still need to use eval(), but with some validation in place, it's not so evil.
function set_user_prop($className, $property,$value) {
if(!class_exists($className)) return false;
if(!property_exists($className, $property)) return false;
/* Since I cannot trust the value of $value
* I am putting it in single quotes (I don't
* want its value to be evaled. Now it will
* just be parsed as a variable reference).
*/
eval($className.'::$'.$property.'=$value;');
return true;
}
class Foo { static $bar = 'Fizz'; }
echo get_user_prop('Foo', 'bar'); // echoes Fizz
set_user_prop('Foo', 'bar', 'Buzz');
echo get_user_prop('Foo', 'bar'); // echoes Buzz
set_user_prop() with this validation should be secure. If people start putting random things as $className and $property, it will exit out of the function as it won't be an existing class or property. As of $value, it is never actually parsed as code so whatever they put in there won't affect the script.
I think this is the simplest:
$foo = new ReflectionProperty('myClassName', 'myPropertyName');
print $foo->getValue();
To return a variable value that is set by a Static Variable you need to call:
$static_value = constant($classname.'::'.$propertyname);
Check out the documentation :: PHP Constant Documentation
You should be able to do something like:
eval("echo $classname::$propertyname;");
I just did a quick test and got this to work for me. Not sure if there's a better way or not, but I wasn't able to find one.
'eval' looks so close to 'evil', and I hate using it and/or seeing it in code. With a few ideas from other answers, here's a way to avoid it even if your php isn't 5.3 or higher.
Changed to reflect testing based on a comment.
class A {
static $foo = 'bar';
}
A::$foo = 'baz';
$a = new A;
$class = get_class($a);
$vars = get_class_vars($class);
echo $vars['foo'];
Outputs 'baz'.
One thing I noticed is that you can't set variables which are protected in static classes as the eval() command runs in a scope outside the class. The only thing to get around this would be to implement a static method inside the/every class which runs the eval(). This method could be protected as the call_user_func() [to call the setter method] also runs from inside the class.
Potentially relevant: discussion on late static binding in PHP - When would you need to use late static binding?.
get_class_vars is not same as get_object_vars.
I think get_clas_vars should return the original property values.
Even if for you said eval is out of the question, prior PHP 5.3 the easiest solution is still by using eval:
eval("\$propertyval = $classname::\$propertyname;");
echo $propertyval;
Getting and setting both static and non static properties without using Reflection
Using Reflection works but it is costly
Here is what I use for this purpose,
It works for PHP 5 >= 5.1.0 because I'm using property_exist
function getObjectProperty($object, $property)
{
if (property_exists(get_class($object), $property)) {
return array_key_exists($property, get_object_vars($object))
? $object->{$property}
: $object::$$property;
}
}
function setObjectProperty($object, $property, $value)
{
if (property_exists(get_class($object), $property)) {
array_key_exists($property, get_object_vars($object))
? $object->{$property} = $value
: $object::$$property = $value;
}
}
You can use ReflectionClass:
class foo
{
private static $bar = "something";
}
$class = "foo";
$reflector = new ReflectionClass($class);
$static_vars = $reflector->getStaticProperties();
var_dump($static_vars["bar"]);