Score:1

How do I get the value of Markup::$string?

kz flag

I have the following code in a custom submit handler:

$status = \Drupal::messenger()->messagesByType('status');
foreach ($status as $delta) {
   // Here I want to extract the text string that is in $delta.
}

The variable $delta now contains this:

delta => stdClass Object
(
    [__CLASS__] => Drupal\Core\Render\Markup
    [string:protected] => Article request My article has been created.
)

How do I get the protected string from $delta?

I've already tried some methods, but so far I haven't found one that works.

Here are those tried so far:

Error: Call to undefined method Drupal\Core\Render\Markup::getMessages()
Error: Call to undefined method Drupal\Core\Render\Markup::toString()

Score:4
in flag

A protected variable is only accessible from the class itself. Your only option to access it from outside the class is via a public method.

Looking at the Markup class, the only public methods are:

  1. count()
  2. jsonSerialize()
  3. __toString()

Simply put, because Markup implements the magic method __toString() (which returns $this->string), you can get that string simply by using the object as a string, e.g. echo $my_markup_object;

Free Radical avatar
kz flag
Thanks! didn't know about the PHP magic methods.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.