kphp icon indicating copy to clipboard operation
kphp copied to clipboard

You can access properties via `$` and its name

Open Danil42Russia opened this issue 2 years ago • 1 comments

<?php

main();

function main() {
  $cls = new TestClass();
  $cls->getName("test");

  var_dump(instance_to_array($cls));
}

class TestClass {
  private string $name;

  function getName(string $name): void {
    $this->$name = $name;
//         ^ <- error is here
  }
}

Output to KPHP:

array(1) {
  ["name"]=>
  string(4) "test"
}

Output to PHP:

array(1) {
  'test' =>
  string(4) "test"
}

Danil42Russia avatar Oct 31 '23 14:10 Danil42Russia

I think we can't access a class field through a value in a variable. There can be two cases in php:

class Test {
  private string $name;
...
}

main();

function main() {
  $cls = new TestClass();
  $cls->getName("name"); // First case
  $cls->getName("test"); // Second case
}

In the first case, we refer to the variable of our class. In most cases, we will not be able to calculate this name in the compile-time. (Cannot be supported in kphp)

In the second case, we create new field of our class. We cannot add new class fields in runtime. (Cannot be supported in kphp)

P.S. Therefore, I think it's worth closing this issue.

Tsygankov-Slava avatar Apr 17 '24 12:04 Tsygankov-Slava