|
Posted by Gordon on June 28, 2008, 12:01 pm
Please log in for more thread options > .oO(Jerry Stuckle)
>
>
>
> >Gordon wrote:
> >> I'm trying to get a constant from a class, where the constant's name
> >> is known, but the class name isn't. =A0I want to do things this way
> >> because I want classes to be able to define certain aspects for their
> >> setup themselves.
> >> [...]
>
> >> echo ($thisClass::VAL);
>
> >> I'm guessing that there is some function that returns a class from a
> >> string, but I can't find it. =A0Can anyone help out here?
>
> >Not real nice, but it can be done...
>
> ><?php
>
> >class FirstClass {
> > =A0 =A0 const VAL =3D 'First val';
> >}
>
> >class SecondClass {
> > =A0 =A0 const VAL =3D 'Second val';
> >}
>
> >$cname =3D 'FirstClass';
> >$str =3D $cname . '::VAL;';
> >eval('echo ' . $str . ';');
> >echo "\n";
>
> >$cname =3D 'SecondClass';
> >$str =3D $cname . '::VAL;';
> >eval('echo ' . $str . ';');
> >echo "\n";
>
> >?>
>
> >Outputs
>
> >First val
> >Second val
>
> >But I don't like it :-)
>
> Neither do I. According to the manual this
>
> echo $thisClass::VAL;
>
> should become possible with PHP 5.3. Until then the Reflection API might
> be another option, but I haven't tried it.
>
> Micha
Thanks. Further investigation turned up the eval() option but I
really don't like using eval(), especially on user-provided data, even
if it has been validated. You never know what you might have missed.
On the other hand reflection might be overkill...
|