3

I am trying to access a private member variable to use as a key in an array.

My class looks similar to this:

<?php
class MyClassName {
  private $value;
  private function MyFunction($array){
    $some_html = "<b> $array[$this->value] <b>"; // error occurring on this line
    return some_html;
  }
}
?>

The error that I am getting is

PHP Parse error: syntax error, unexpected '-', expecting ']

If I store the private member variable before using it in the array there is no syntax error. This is interpreted fine:

<?php
class MyClassName {
  private $value;
  private function MyFunction($array){
    $cache_key = $this->value;
    $some_html = "<b> $array[$cache_key] <b>";
    return $some_html;
  }
}
?>

Is there something I am missing? I want to improve my understanding of what is happening here. Thanks.

4
  • And what does MyFunction returns, actually, when you run it (in second case)? Commented Oct 13, 2015 at 18:02
  • There is nothing wrong with your first example, and in the second you are copying the $value to $cache_key but not using it. My guess is that there is a syntax error somewhere in your real code. Commented Oct 13, 2015 at 18:04
  • Works here: 3v4l.org/MgG62 Commented Oct 13, 2015 at 18:07
  • Sorry about that I updated the examples to more closely show what is going on. I am trying to return a string. Commented Oct 13, 2015 at 18:18

1 Answer 1

1

Try this:

$some_html = "<b> ".$array[$this->value]." </b>";
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @DNT that fixed my problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.