Mohammad Saberi
Mohammad Saberi

Reputation: 13166

syntax error while using php pack() function inside class

I must use PHP pack() function to do something in my codes. But when I do it inside a class, I get the errors below. Whereas if I use it normally (without using in class), it works without any error.

class encryption
{
    $my_key = pack('H*', "123456");
}

and this is the error:

Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in ...

Also if I use public for $my_key, I will get a new error.

class encryption
{
    public $my_key = pack('H*', "123456");
}

Error:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in ...

What is wrong in my codes?

Upvotes: 0

Views: 101

Answers (2)

viral
viral

Reputation: 3743

class encryption
{
    public $my_key;

    public function __construct()
    {
         $this->my_key = $this->pack('H*', "123456");
         // will always be executed when you create an object of this class
    }

    private function pack($arg1, $arg2)
    {
        // return something
    }
}

Upvotes: 0

gabe3886
gabe3886

Reputation: 4265

When defining a variable for a class outside of a function, you can't use another function to define it. If you need it to have that value when initialised, set the value in the constructor function. Your class will then look like :

class encryption
{
    public $my_key;

    public function __construct() {
        $this->my_key = pack('H*', "123456");
    }
}

Upvotes: 2

Related Questions