-3

I'm trying to return an Array of Strings in a function within my class

When I try to use a private static array it returns me the following error:

Fatal error: Constant expression contains invalid operations in /home/developer/projects/api/src/public/Sql.php on line 17

This is my Class

<?php

namespace App;

/**
* Class Sql
*
* @return (Array) (Strings)
*/

Class Sql {
  private static $columns = (implode(",", array('product_id','model','viewed','ups','downs','location','price','quantity')));

  public function getColumns() {
    echo "<pre>";
    print_r(self::$columns);
    echo "</pre>";
    exit();
  }
}

Is there a problem in syntax or am I doing something I should not do?

What would be the right thing to do?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    Because your calls to implode is not static, and must be resolved at runtime. Constants must be truly defined as constants. – Matt Clark Apr 08 '19 at 21:11
  • 1
    you can't use an expression for a static variable. That means you cant use implode in your assignment just call it in your constructor or the method where you access the static variable. – Orlando P. Apr 08 '19 at 21:12
  • @Matt Clark, thank you for your answer! Not a duplicate, who scored as a duplicate, did not understand what I actually asked – Mateus Felipe Apr 09 '19 at 18:29
  • Your question is no different the the one marked as a dupe. You both try to dynamically assign a constant, which you can not do. – Matt Clark Apr 09 '19 at 18:40

1 Answers1

0

Try

private static $columns = ['product_id','model','viewed','ups',
                           'downs','location','price','quantity'];

I don't see why you're using implode anyway, since that would only result in $columns being a string (it would 'glue' the items in a single string: product_id,model,viewed,ups...).

RobIII
  • 8,488
  • 2
  • 43
  • 93
  • Thanks, but that's not what I asked. I asked if the problem occurred because of syntax error or if what I was doing was impossible. As responded by @Matt Cark – Mateus Felipe Apr 09 '19 at 18:33
  • @MateusFelipe You *literally* asked: "What would be the right thing to do?". My answer is exactly that; the right thing to do. – RobIII Apr 09 '19 at 21:58