Search code examples
phparraysclassvariablesglobal-variables

Use variable in an class and in an function with array


$n=800; 
function getName($n) { 
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
    $randomString = ''; 

    for ($i = 0; $i < $n; $i++) { 
        $index = rand(0, strlen($characters) - 1); 
        $randomString .= $characters[$index]; 
    } 

    return $randomString; 
} 

$secretcode = getName($n);

class Mess {
    protected static $options = array(
        'secret' => '$secretcode',
        'signing_method' => 'sha512',
        'verify' => true,
    );
}

This is my PHP code as shown, i want the variable "secretcode" or the value in this variable to put in at the position in the class where is an function with an array. In this array at the secret element of the array should be the varibale value. I heard about global variable but i tried so much with it, everytime it gives me error specific what i change back but i dont understand why things not work. Honest im have not used php classed yet so i dont know if it diffent usage with varibale then normal.


Solution

  • You can use this as inside the class

    class Mess {
        protected static $options = array(
         'secret' => '',
         'signing_method' => 'sha512',
         'verify' => true,
        );
        function __construct($number){
          !empty(self::$options['secret']) ? self::$options['secret'] : this->getName($number);
        }
        function getName($n) { 
          $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
          $randomString = ''; 
          for ($i = 0; $i < $n; $i++) { 
            $index = rand(0, strlen($characters) - 1); 
            $randomString .= $characters[$index]; 
          } 
          return $randomString; 
        } 
    }