0

I'm trying to assign $GLOBALS['a'] variable in function from class, but haven't succeeded.

Here is my code:

<?php

 $GLOBALS['a'] = "alter";

 class db_data 
 {
   public $a;

   function __construct()
   {
     $this->a = $GLOBALS['a']; 
   }

 }

 $db = new db_data;

 echo $db->$a;

?>

And produced this error:

Notice: Undefined property: db_data::$alter.....

I tried to search on SO for this, but all questions were different and it did not resolve my problem.

4
  • echo $db->$a; or echo $db->a; remove $ Commented Jun 14, 2013 at 18:32
  • 1
    To access an object's properties, you need echo $db->a; Commented Jun 14, 2013 at 18:32
  • 2
    stop using globals or stop using class, by using one you negate the benefit of the other. Commented Jun 14, 2013 at 18:34
  • ((( always same error - syntax/inattention. Thanks a lot! )) Commented Jun 14, 2013 at 18:35

1 Answer 1

2

Answers are in the question comments, but here's why it's happening

You're accidentally using the variable variables feature of PHP. When you call $thing->$a, you're actually getting the value of $a (which defined by the $GLOBALS['a'] = "alter"; line), and then getting the property of $thing with that value.

As stated in your comments, you should simply echo $db->a, as that's how PHP properties are accessed

Also, Watch out!, if the value of $a is changed elsewhere in the global scope, your db_data class will reflect that change, which you probably don't want.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, For watch out - thats exactly what i need. if it changes, i want to use it.
another thing if i'm asking - what difference between -> and :: ?
The double colon, called the Scope Resolution Operator, is for referencing static properties or methods on a class. Basically, a static method/property is just attached to a class, rather than in instance of that class. In my opinion, the error message should show -> instead of ::, but it's PHP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.