Daniel Buckmaster
Daniel Buckmaster

Reputation: 7186

Initialize a class property

Is there a way to initialize a PHP class property from another class property? I have a series of properties I'd like to depend upon each other for easy modification of the root value:

class Anon {
    private static $a = 5;
    private static $b = '+' . (2 * self::$a);
}

However, this causes a syntax error. I've had trouble searching for this, but I haven't seen anybody trying to do this!

Upvotes: 0

Views: 280

Answers (4)

cpk
cpk

Reputation: 809

You can't access private class properties directly. You can with public though.

class Anon {
    public static $a = 5;
}

print Anon::$a;

or use a public function like the other examples to access $b;

class Anon {

    private static $a = 5;
    private static $b;

    public static function init() {
        return self::$b = '+' . (2 * self::$a);
    }
}

echo Anon::init();

Upvotes: 1

Kheshav Sewnundun
Kheshav Sewnundun

Reputation: 1244

You can initialise the static variable by using an Init method

   <?php
    class Anon {
        private static $a = 5;
        private static $b ;
        public static function Init(){
            self::$b = '+' . (2 * self::$a);
        }
        public static function getB(){
            return self::$b;
        }
    }
    Anon::Init();
    echo Anon::getB();
    ?>

Upvotes: 3

Halayem Anis
Halayem Anis

Reputation: 7785

Unfortunately PHP can not parse non-trivial expression while class is being loaded
Here is a solution to initialize your static members

    class Anon {
      private static $a;
      private static $b;

    public static function init () {
        self::$a = 5;
        self::$b = '+' . (2 * self::$a);
    }
   }

Anon::init();

Upvotes: 1

grimmdude
grimmdude

Reputation: 374

Depends on how you're using the class, but maybe this will help:

class Anon {
    private static $a = 5;
    private static $b;

    function __construct() {
        self::$b = '+' . (2 * self::$a);
    }

    public function getB() {
        return self::$b;
    }
}

$anon = new Anon;
echo $anon->getB();

Upvotes: 1

Related Questions