Hello,

How can I declare an array as a class variable? For example I can do:

<?php
class test {

private $name = 'john';

public function getName() {
  return $this->name;
} 

}
?>

But how can I make the following work?

<?php
class test {

private $name = array();
private $name[] = 'john';
private $name[] = 'jenny';

public function getName() {
  return $this->name;
} 

}
?>

Dani AI

Generated

What trips up your second snippet, ryy705, is that property initializers in a class must be a single constant expression. You cannot run statements like $name[] = 'john'; at class scope. Arrays are fine as defaults, but they must be declared in one expression. somedude3488’s constructor approach solved that for older code, but in modern PHP you can set the array right on the property. (php.net)

<?php
// PHP 7.4+ (typed property)
class Test {
    private array $names = ['john', 'jenny'];

    public function getNames(): array {
        return $this->names;
    }
}

If you must support older versions, drop the type and this still works. For very old PHP (<=5.3), use array('john','jenny') instead of ['john','jenny'] because short array syntax was added in PHP 5.4. (php.net)

Another clean option today is constructor property promotion (PHP 8.0+), which keeps somedude3488’s idea but cuts the boilerplate:

<?php
class Test {
    public function __construct(private array $names = ['john','jenny']) {}
    public function getNames(): array { return $this->names; }
}

Property promotion declares and assigns the property from the constructor signature, so you do not need a separate class property line. (php.net)

Troubleshooting tips:

  • If you need to compute elements (e.g., from config or I/O), do it in __construct() and assign once to the property. Do not attempt $this->names[] = ... at class scope. (php.net)
  • Prefer public/protected/private over the legacy var seen in very old code. Property promotion, in particular, does not allow var. (php.net)

Recommended Answers

All 3 Replies

you need to use a constuctor

<?php
class test {
  var $name = array();
  //this function used to make class PHP4 compatible
  function test() {
    $this->__construct();
  }
  function __construct() {
    $this->name = array('john','jenny');
  }
  function getName() {
     return $this->name;
  }
}
?>

how can i declare an array variable as a class property

how can i declare an array variable as a class property

See previous post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.