-3
<?php

class foo
{
    public $a;

    public function __construct()
    {
        $a='value';
    }

}

$class = new foo();
echo $class->$a;

?>

I want to use the value $a in other parts of my script.

How do I retrieve a variable set in a php object and use it for other things outside of the object?

seamus
  • 2,681
  • 7
  • 26
  • 49
  • 1
    Tons of good advice/examples on the PHP documentation: http://php.net/manual/en/language.oop5.php – Jasper Aug 02 '13 at 16:31

3 Answers3

2

To set the value inside a method, the syntax is:

$this->a = 'value';

To obtain the value of the property from an instance of the class, the syntax is:

$foo = new foo();
echo $foo->a;

The Properties manual page goes into more detail.

rid
  • 61,078
  • 31
  • 152
  • 193
2

I'd recommend using a getter (see):

Inside your class.

private $a;

public function getA()
{
    return $this->a;
}

Outside your class.

$class = new foo();
echo $class->getA();

Important: Inside your class you should refer to $a as $this->a.

Community
  • 1
  • 1
federico-t
  • 12,014
  • 19
  • 67
  • 111
1

Use $this variable to assign and reference instance variables and functions on the current object.

In your case replace $a = 'value'; with $this->a = 'value';

vee
  • 38,255
  • 7
  • 74
  • 78