Rohit Chopra
Rohit Chopra

Reputation: 2821

Can I pass a DEFINED constant to a function through a variable in PHP?

I have the following code:

DEFINE('DEFINEDTESTVAR', 'Hello World');

function callit($callVar) {
  echo "The call is ".$callVar;
}


$passthis = 'DEFINEDTESTVAR';
callit($passthis);

I know I can do callit(DEFINEDTESTVAR) but that's not what I am looking to do. Is it possible?

Upvotes: 1

Views: 7693

Answers (4)

Gaurav
Gaurav

Reputation: 28755

define('DEFINEDTESTVAR', 'Hello World'); // you should use define

function callit($callVar) {
  echo "The call is ".$callVar;
}    

$passthis = DEFINEDTESTVAR; // no need to use quotes
callit($passthis);

Upvotes: 3

Gordon
Gordon

Reputation: 1914

You can get a constant's value from a string with constant(). It will return null if the named constant is not found.

$passthis = constant('DEFINEDTESTVAR');
callit($passthis);

Upvotes: 1

BoltClock
BoltClock

Reputation: 723598

Either pass the constant itself:

$passthis = DEFINEDTESTVAR;

Or access it through constant() which allows you to test for null in case it isn't defined (for undefined constants, passing the constant literally results in a string with the constant name):

$passthis = constant('DEFINEDTESTVAR');

Upvotes: 9

Manish Trivedi
Manish Trivedi

Reputation: 3559

<?php 
DEFINE('DEFINEDTESTVAR', 'Hello World');

function callit($callVar) {
  echo "The call is ".$callVar;
}


$passthis = DEFINEDTESTVAR;
callit($passthis);

Upvotes: 0

Related Questions