Andrew Ozarko
Andrew Ozarko

Reputation: 1

Name in the Properties class

Problem: get the name of a class property.

<?php 

class Vasya {
    public $name = __CLASS__;
}

$class = new Vasya();
echo $class->name; // result Vasya

class Petro extends Vasya { }

$class = new Petro();
echo $class->name; // result Vasya // Why???

How to get the name of a class inherited in property?

Upvotes: 0

Views: 36

Answers (1)

Thamilhan
Thamilhan

Reputation: 13303

It is because, $name is declared only in the Parent Class; So it holds the class name of parent class. If you want your child class name, declare the variable in Child Class. In that case, it overrides the parent class's variable:

<?php

class Vasya {
    public $name = __CLASS__;
}

$class = new Vasya();
echo $class->name; // result Vasya

class Petro extends Vasya { 
    public $name = __CLASS__;
}

$class = new Petro();
echo $class->name; // result Petro

Upvotes: 1

Related Questions