FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Usage of class constants inside strings and heredocs
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: Usage of class constants inside strings and heredocs [message #170510 is a reply to message #170509] Thu, 04 November 2010 09:16 Go to previous messageGo to previous message
alvaro.NOSPAMTHANX is currently offline  alvaro.NOSPAMTHANX
Messages: 277
Registered: September 2010
Karma:
Senior Member
El 04/11/2010 10:01, Giuseppe Sacco escribió/wrote:
> Hi all,
> just to be sure: when you suggest to use sprintf(), do you mean
> something like this?
>
> <?php
>
> class myTable {
> const F_CODE = "code";
> const F_DESCRIPTION = "description";
> const TABLENAME = "lookup";
> public function insert($record)
> {
> // simplified: does not escape strings, does not use prepared
> statemnts
> $sql = sprintf("INSERT INTO %s (%s,%s) VALUES ('%s', '%s')",
> self::TABLENAME, self::F_CODE, self::F_DESCRIPTION,
> $record[self::F_CODE], $record[self::F_DESCRIPTION]);
>
> echo $sql;
> } // end method insert
>
> } // end class myTable
>
> $record = array(
> 'code' => 'This is the code',
> 'description' => 'This is the description',
> );
> $foo = new myTable;
> $foo->insert($record);
>
> ?>

IMHO this looks cleaner than your original approach but you can combine
all ideas to your liking, e.g.:

$sql = <<<SQLQ
INSERT
INTO %s (%s, %s)
VALUES ('%s', '%s')
SQLQ;

$sql = sprintf($sql,
self::TABLENAME, self::F_CODE, self::F_DESCRIPTION,
$record[self::F_CODE], record[self::F_DESCRIPTION]);

Or even:

$sql = sprintf(<<<SQLQ
INSERT
INTO %s (%s, %s)
VALUES ('%s', '%s')
SQLQ;
, self::TABLENAME, self::F_CODE, self::F_DESCRIPTION,
$record[self::F_CODE], $record[self::F_DESCRIPTION]);

I particularly love arrays and I tend to abuse them:

$sql = "INSERT
INTO {table} ({f_code}, {f_description})
VALUES ('{r_code}', '{r_description}')";

$replacements = array(
'{table}' => self::TABLENAME,
'{f_code}' => self::F_CODE,
'{f_description}' => self::F_DESCRIPTION,
'{r_code}' => $record[self::F_CODE],
'{r_description}' => $record[self::F_DESCRIPTION]
);

$sql = strtr($sql, $replacements);


You should not run out of ideas :)

--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://borrame.com
-- Mi web de humor satinado: http://www.demogracia.com
--
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Free Web Space for our Experiments
Next Topic: There is some framework/tool to generate PHP code
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Thu Nov 14 01:30:31 GMT 2024

Total time taken to generate the page: 0.04400 seconds