Skip to content

Core\Uri::toString

$uri->toString(): string

Returns the address as text. For a Uri that Core\Uri::parse read, the result is exactly the text that was read, byte for byte. Nothing is changed: HTTP://Example.COM/a%2fb comes back as HTTP://Example.COM/a%2fb, with the same upper-case letters and the same escapes.

For a Uri that with, withQueryParameter or resolved made, the result is the new address.

echo $uri prints the same text as echo $uri->toString(). Use toString() when you need a string, for example to store the address or to return it from a function.

Two texts can be the same address, such as HTTPS://Example.com/ and https://example.com/. toString keeps them different. compareTo checks if two addresses are the same.

The examples below print an address unchanged, compare two ways to write one address, and build the Link header of an API.

Return value

Returns string. The address as a string. For HTTP://Example.COM/a%2fb the result is HTTP://Example.COM/a%2fb.

Examples

The text comes back unchanged

<?nvs
// Shows that `toString` returns an address exactly as it was written.
var $uri = Core\Uri::parse('HTTP://Example.COM/a%2fb');
// Upper-case letters and the escape `%2f` do not change.
// This prints HTTP://Example.COM/a%2fb.
echo $uri->toString(), "\n";
// `echo` prints the same text. This prints HTTP://Example.COM/a%2fb again.
echo $uri, "\n";
// A relative link comes back unchanged too. This prints /docs/start?page=2.
echo Core\Uri::parse('/docs/start?page=2')->toString(), "\n";
Output
HTTP://Example.COM/a%2fb
HTTP://Example.COM/a%2fb
/docs/start?page=2

Two ways to write one address

<?nvs
// Shows that `toString` keeps two ways to write one address different.
var $a = Core\Uri::parse('HTTPS://Example.com/~anna');
var $b = Core\Uri::parse('https://example.com/%7Eanna');
// The texts are different, so this prints "different texts".
string $textA = $a->toString();
string $textB = $b->toString();
echo $textA == $textB ? 'same text' : 'different texts', "\n";
// `compareTo` checks the address. It returns 0 when both are the same address, so this prints 0.
echo $a->compareTo($b), "\n";
Output
different texts
0

Build a link header

<?nvs
// Shows how an API builds the `Link` header that points to the next page of results.
class NextPage
{
public static function header(Core\Uri $current, int $page): string
{
// `toString` gives the new address as a `string`.
string $next = $current->withQueryParameter('page', $page + 1)->toString();
return '<' . $next . ">; rel=\"next\"";
}
}
var $request = Core\Uri::parse('https://api.example.com/orders?status=open&page=1');
// This prints <https://api.example.com/orders?status=open&page=2>; rel="next".
echo NextPage::header($request, 1), "\n";
Output
<https://api.example.com/orders?status=open&page=2>; rel="next"