Jump to content

Can use a function when defining a protected class variable


Go to solution Solved by Jacques1,

Recommended Posts

Apologies if this is a very simple question, as the problem highlights itself as a compiler error. I'm a self taught PHP programmer, so I'm probably misunderstanding something from the object orientated side of things - but despite some googling, it's got me stumped as to how to get around it.

 

I came across the issue when I had to make some fixes to someone else's phpunit code. They had a protected array in a class with one of the key values set as XML text. However, I found that it needed to be converted to a SimpleXMLElement. So I tried converting using simplexml_load_string(). However, this just resulted in the syntax error:

 

       PHP Parse error:  syntax error, unexpected '(', expecting ')'

 

I didn't understand this, so I stripped down to a simple standalone example which replicates the problem:

<?php
class problemDemo
{
    protected $Len = strlen('MY_TEXT');
}
?>
So can anyone explain why I can't set a protected variable value within a class using a function? Is there any alternative way to get around?
 

 

PS. Apologies for post subject - it should have said "CAN'T use a function when defining a protected class variable"!

Edited by whitburn
  • Like 1
  • Solution

Initialization values of properties are evaluated at compile-time, so you can't use arbitrary expressions (you're mostly limited to constant values).

 

To get around this, you can use a constructor to set the property value when the object is created:

<?php



class Demo
{
    protected $len;

    public function __construct()
    {
        $this->len = strlen('MY_TEXT');
    }

    public function getLen()
    {
        return $this->len;
    }
}


$demo = new Demo();
var_dump($demo->getLen());

  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.