Variables

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kardon33
    New Member
    • May 2007
    • 158

    Variables

    In php can u name a variable from the contents of another varible or array.
  • mwasif
    Recognized Expert Contributor
    • Jul 2006
    • 802

    #2
    Yes you can. This is called variable variable.

    Comment

    • Purple
      Recognized Expert Contributor
      • May 2007
      • 404

      #3
      Hi kardon33,

      Whilst you can, it doesn't have to mean you should..

      I can't think of a good reason to do this.

      I personally prefer to write code most other people can understand..

      Some good reasons not to do this are you can't use variable variables within functions or class methods.

      Just my thoughts..

      Purple

      Comment

      • mwasif
        Recognized Expert Contributor
        • Jul 2006
        • 802

        #4
        Originally posted by Purple
        Some good reasons not to do this are you can't use variable variables within functions or class methods.
        Are you sure about this?

        PHP Manual says
        Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods.

        Comment

        • pbmods
          Recognized Expert Expert
          • Apr 2007
          • 5821

          #5
          Here's an example that I like to use a lot:

          [code=php]
          /**
          * __get
          *
          * Generic accessor
          *
          * @param string $var The name of the variable
          *
          * @return mixed $this->my$var or $this->myData[$var]
          */
          public function __get($var) {
          $target = ('my' . ucfirst($var = strtolower($var )));
          if(isset($this->$target))
          return $this->$target;
          return $this->myData[$var];
          }
          [/code]

          Comment

          Working...