E
E
EarthFM2014-08-25 14:22:45
PHP
EarthFM, 2014-08-25 14:22:45

How to work with properties in php?

Why does this code work if $this->name refers to a field, but this field does not exist? In java, there will be an error right away, but here everything is displayed)

<?php

class User {
  public function __construct($name, $age) {
    $this->name = $name;
    $this->age = $age;
  }
  public function getName() {
    return $this->name;
  }
  public function getAge() {
    return $this->age;
  }
}

$obj = new User("Ilya", 11);
echo $obj->getName();
echo $obj->getAge();

?>

And when the Student class is inherited from User. In the constructor, we refer to the fields of the superclass, but they are not there and everything works smoothly. Why does it work like this, or somehow it is necessary to write differently, explain pliz.
<?php
require_once 'index.php';

class Student extends User {
  public function __construct($name, $age) {
    parent:: __construct($this->name=$name, $this->age=$age);
  }
}

$obj = new Student("Ilya", 2222);
echo $obj->getName() . "<br/>";
echo $obj->getAge() . "<br/>";

?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nepster-web, 2014-08-25
@EarthFM

Like in php.ini it is possible to expose "rigidity" of errors.
php.net/manual/ru/function.error-reporting.php Yours
is probably not hard. Usually such "simple" moments as calling a non-existent variable are ignored in errors.
But in any case, you can customize to taste.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question