Joe
Joe

Reputation: 3834

Access a property of an object inside a method of that class

I'm trying to access a property of an object inside a method of that class. Here's what I have so far:

class Readout{
    private $digits = array();
    public function Readout($value) {
        $length = strlen($value);
        for ($n = 0; $n < $length; $n++) {
            $digits[] = (int) $value[$n];
        }
    }
}

The goal is to be able to say $x = new Readout('12345'), where this creates a new Readout object with its $digits property set to the array [1,2,3,4,5].

I seem to recall there's some issue with scope in PHP, where $digits might not be visible inside Readout, so I tried replacing $digits[] = with $this->$digits[] =, but that gave me a syntax error.

Upvotes: 0

Views: 74

Answers (4)

Sam Arul Raj T
Sam Arul Raj T

Reputation: 1770

This works as well

<?php
class Readout{
    public $digits = array();
    public function Readout($value) {

        $this->digits = implode(',',str_split($value));


     }
}

$obj = new Readout(12345);

echo '['.$obj->digits.']';

?>

Upvotes: 0

Brian
Brian

Reputation: 3023

That's because the correct way to call variables in a class varies based on whether you're accessing them as static or instanced (non-static) variables.

class Readout{
    private $digits = array();
    ...
}

$this->digits; //read/write this attribute from within the class

class Readout{
    private static $digits = array();
    ...
}

self::$digits; //read/write this attribute from within the class

Upvotes: 0

Martin Rothenberger
Martin Rothenberger

Reputation: 828

The right syntax to access a class property inside a class method in your case is:

$this->digits[];

To create a new Readout object with 12345 set, you have to implement the class like this:

class Readout {
    private $digits = array();

    public function __construct($value)
    {
        $length = strlen($value);
        for ($n = 0; $n < $length; $n++) {
            $this->digits[] = (int) $value[$n];
        }
    }
}

$x = new Readout('12345');

Upvotes: 0

dweeves
dweeves

Reputation: 5605

the good syntax is:

$this->digits[]

Upvotes: 2

Related Questions