PHP task: what will the `$user` and `$product` variables contain when the static method `getTableName()` is called in the `User` and `Product` subclasses? Explain your reasoning.
Asked at
AI answer
The exact result depends on the method's code and classes, which are not provided in the question. An important PHP rule is late static binding. In an inherited static method, static:: refers to the class through which the method was called, while self:: refers to the class where the method was declared.
class Model
{
public static function getTableName(): string
{
return static::$table;
}
}
class User extends Model { protected static string $table = 'users'; }
class Product extends Model { protected static string $table = 'products'; }
$user = User::getTableName(); // 'users'
$product = Product::getTableName(); // 'products'
If the method returns static::class, the values will be 'User' and 'Product'; with self::class in the Model method, both calls will return 'Model'. Therefore, to give an exact answer, we need to know the implementation of getTableName() and the property declarations.
Also asked at SkyCoach
Similar questions
- Какой будет результат вывода? Почему? ```php class Foo { protected static $name = 'Foo'; public static function getName() { return static::$name; } } class Bar extends Foo { protected static $name = 'Bar'; } echo Bar::getName(); ``` Что будет выведено и почему? ```php $controlScore = 1; $a = 0.7; $b = 0.3; $result = $controlScore - $a - $b; if ($result > 0) { echo 'Access granted!'; } else { echo 'Access denied!'; } ```
- How do the keywords self:: and static:: differ in the context of calling methods and properties in PHP?
- How can you bypass or eliminate the difficulties associated with inheritance in PHP?
- How would you improve the way the status value is stored and handled?
- What happens if a subclass calls a method that is not defined in it using self::?