0

I was curious when I first tried PHP, I just heard the term variable function, when I wanted to try it in class, the code was like this:

<?php

class example{
    var $func = function () {
            return 1 + 2;
        };
    var $fn = fn() => 1+2;
}

its give error : PHP Fatal error: Constant expression contains invalid operations in /var/www/html/phpmvc/latihan.php on line 4

is arrow function or anonymous function actually cant declare in class?

iam New btw

Rogan
  • 1
  • 1
  • 2
    *"variables in the class"* are called **properties** and you really shouldn't declare them with `var` (it's 2023, what about a typed property with explicit visibility declared using constructor property promotion ?). Other than properties, classes can contain functions, called **methods**, do you really need to store a function as a property's value ? If you still need to do this, just don't declare the function in the property declaration as it tries to set the property default value which must be a "constant expression" (no function declaration/call), declare it in the constructor instead. – AymDev Jan 05 '23 at 08:51
  • See also this https://stackoverflow.com/questions/1633012/initialize-class-property-with-an-anonymous-function it explains it very well – user1915746 Jan 05 '23 at 13:31

0 Answers0