4

Is it possible to define a PHP class property and assign the value dynamically using a property within the same class? Something like:

class user { public $firstname = "jing"; public $lastname = "ping"; public $balance = 10; public $newCredit = 5; public $fullname = $this->firstname.' '.$this->lastname; public $totalBal = $this->balance+$this->newCredit; function login() { //some method goes here! } } 

Yields:

Parse error: syntax error, unexpected '$this' (T_VARIABLE) on line 6

Is anything wrong in the above code? If so, please guide me and if it is not possible then what is a good way to accomplish this?

2 Answers 2

11

You can put it into the constructor like this:

public function __construct() { $this->fullname = $this->firstname.' '.$this->lastname; $this->totalBal = $this->balance+$this->newCredit; } 

Why can't you do it the way you wanted? A quote from the manual explains it:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

For more infromation about OOP properties see the manual: http://php.net/manual/en/language.oop5.properties.php

Sign up to request clarification or add additional context in comments.

3 Comments

@Yuvi At initialization in the class definition it has to be a constant value which can be evaluated at compile time; In the constructor or other functions you can assign what you want
What if we want to access the dynamic property in a child class? How do you call it? I am facing challenge in that.
@andex As long as you don't overwrite the property in your child class you can just access it like this: $this->yourProperty
2

No, you cannot set properties like that.

However: you can set them in the constructor, so they will be available if someone creates an instance of the class :

public function __construct() { $this->fullname = $this->firstname . ' ' . $this->lastname; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.