Calling Methods Inside Classes in OOP in PHP
Some methods can be called inside
others via $this
. Let's
look at an example. Suppose we have
a class with a user and a method
that returns a property:
<?php
class User {
public $name;
public function show() {
return $this->name;
}
}
?>
Suppose we also have a method cape
,
which converts the first letter of a string
to uppercase:
<?php
class User {
public $name;
public function show() {
return $this->name;
}
public function cape($str) {
return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
}
}
?>
Let's use the method cape
inside the method show
:
<?php
class User {
public $name;
public function show() {
return $this->cape($this->name);
}
public function cape($str) {
return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1);
}
}
?>
Make a class Student
with properties name
and surn
.
Make a helper method, which will get the first character of a string and make it uppercase.
Make a method that will return the student's initials, that is, the first letters of their first name and last name.