Retrieve public class properties with PHP’s arrow syntax
We already created a constructor in the Author class, which executes when a class is created, or instantiated. Since this $name class property has a public visibility, we can refer to it directly with the arrow syntax.
Let’s go ahead and assign this Author instance in our functions.php file to an $author1 variable. We’ll also create another author, so let’s duplicate this line out for the second author, and we will name this one Betsy Sue.
<?php declare(strict_types=1);
require('classes/Author.php');
function getPosts(): array
{
$author1 = new Author('Mark Shust');
$author2 = new Author('Betsy Sue');
We can now assign these values to new author values on the posts array. We can reference the $name class property directly after an array, since this name class property is public in scope.
<?php declare(strict_types=1);
require('classes/Author.php');
function getPosts(): array
{
$author1 = new Author('Mark Shust');
$author2 = new Author('Betsy Sue');
return [
[
'title' => 'How to learn PHP',
'content' => 'This is how you learn PHP.',
'author' => $author1->name,
],
[
'title' => 'How to learn MySQL',
'content' => 'This is how you learn MySQL.',
'author' => $author1->name,
],
[
'title' => 'How to learn Nginx',
'content' => 'This is how you learn Nginx.',
'author' => $author2->name,
],
];
}
function getPostText(int $numPosts): string
{
return $numPosts === 1 ? 'post' : 'posts';
}
We want to now display the author on our page, so let’s go back to the index.php file and add a “by” line that references this new author index on the posts array.
<?php declare(strict_types=1);
require('functions.php');
$title = 'My Blog';
$posts = getPosts();
$numPosts = count($posts);
$postText = getPostText($numPosts);
$numPostsDisplay = "$numPosts $postText";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?php for ($i = 0; $i < $numPosts; $i++) : ?>
<h3><?= $posts[$i]['title'] ?></h3>
<p><?= $posts[$i]['content'] ?></p>
<p>By <?= $posts[$i]['author'] ?></p>
<?php endfor ?>
When we refresh the page, we now see the author’s name next to each blog post.