L
L
Lander2015-09-30 09:44:51
PHP
Lander, 2015-09-30 09:44:51

Is it possible to use constants in constants?

Good afternoon.
I decided here in one small project without PDO and ORM to put all requests into a separate class. To increase flexibility, I want to do this:

<?php

class Query
{
  const TABLE_PREFIX = 'prefix_';	
  
  const TABLE_ENTITYES = 'entity';

  //?i - плейсхолдер для обёртки над mysqli
  const GET_ENTITY_BY_ID = '
    SELECT
      `id` AS id,
      `name` AS name,
      `origin` AS domain,
      `token` AS token
    FROM 
      ' . self::TABLE_PREFIX . self::TABLE_ENTITYES . '
    WHERE
      `id`=?i
    LIMIT 1';
}
 
$queryString = Query::GET_ENTITY_BY_ID; //обращение к запросу

But PHP doesn't seem to allow constants in constants. Is there an option to somehow make it work or do you still have to fiddle with getters and introduce some kind of templating? I don’t want to create a separate instance of the class, but I want to get everything statically.
I want a lot, don't I? :)
Thanks in advance :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
index0h, 2015-09-30
@index0h

In 5.6 - you can, there are cases for this, for example, groups of constants in arrays. But your SQL in constants is:
Either make a static variable directly inside the method (which is also not good really), or just a method that will return your SQL line.

C
Cat Anton, 2015-09-30
@27cm

In PHP 5.6, constant expressions should work:
php.net/manual/ru/migration56.new-features.php
But if you really want to use the old version, you can do this trick:

<?php

define('QUERY_TABLE_PREFIX', 'prefix_');
define('QUERY_TABLE_ENTITYES', 'entity');
define('QUERY_GET_ENTITY_BY_ID', 
    'SELECT `id` AS id, `name` AS name, `origin` AS domain, `token` AS token ' . 
    'FROM ' . QUERY_TABLE_PREFIX . QUERY_TABLE_ENTITYES . ' ' .
    'WHERE `id`=?i LIMIT 1'
);

class Query
{
  const TABLE_PREFIX = QUERY_TABLE_PREFIX;	
  
  const TABLE_ENTITYES = QUERY_TABLE_ENTITYES;

  const GET_ENTITY_BY_ID = QUERY_GET_ENTITY_BY_ID;
}
 
$queryString = Query::GET_ENTITY_BY_ID;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question