Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an object twice in string

Tags:

php

I've noticed this in PHP and MySQL when I've been trying to put some object values in my query. I did some google searching for "Accessing object property twice" and "-> PHP twice", but couldn't find much results. I think it's the way PHP processes strings and wanted a bit more information. This is my question:

<?php
class Object {
    public function __construct() {
        $this->a = new A();
        echo "This x is '$this->a->x'";
    }
}

class A {
    public function __construct() {
        $this->x = 1;
    }
}

$object = new Object();
?>

The above code will raise an error: E_RECOVERABLE_ERROR : type 4096 -- Object of class A could not be converted to string -- at line 5

However, if we give it a temporary variable like this:

<?php
class Object {
    public function __construct() {
        $this->a = new A();
        $x = $this->a->x;
        echo "This x is '$x'";
    }
}

class A {
    public function __construct() {
        $this->x = 1;
    }
}

$object = new Object();
?>

Then it works completely fine, or if we concatenate it, it also works fine

<?php
class Object {
    public function __construct() {
        $this->a = new A();
        echo "This x is '" . $this->a->x . "'";
    }
}
?>

Double quoted PHP strings are supposed to be able to recognize variables prefixed with $ and automtically substitute them. This also works fine if we're only accessing the object property once (-> single). I think the PHP double-quoted string stop processing after a single -> thus the reason for th error:

E_RECOVERABLE_ERROR : type 4096 -- Object of class A could not be converted to string -- at line 5

Which makes sense if it is only being accessed once (since $this->a is still an object). I'm not entirely convinced and could not find much information on this in PHP, so I was wondering if anyone could elaborate or detail me more on this and why it happens?

like image 227
q.Then Avatar asked Sep 03 '26 23:09

q.Then


1 Answers

You are correct. PHP only takes $this->a as variable. You can see this also in the PHP manual:

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

This means in a double quoted string:

$arr[0][1] = "X"; 
echo "$arr[0][1]";  //Same as echo $arr[0] . "[1]";

$o = (object)["a" => (object)["b" => "X"]];
echo "$o->a->b";    //Same as echo $o->a "->b";

So to solve this you have to use complex curly syntax, e.g.

echo "{$o->a->b}";
      ↑See here↑ 

With this you can explicit define what the variable is and what normal string is.

like image 186
Rizier123 Avatar answered Sep 05 '26 12:09

Rizier123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!