Z
Z
zooks2014-08-05 08:30:50
PHP
zooks, 2014-08-05 08:30:50

Why are undefined object properties displayed in PHP?

Good morning. I deliberately made a mistake in the name of the variable when it was defined. But the code still works. What can you advise?

<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);

class Customer {

  var $name1;//error here
  var $lastname;

  function getName() {
    echo 'Name: ';
    echo $this -> lastname;
  }

  function setName($name) {
    $this -> name = $name;
    $this -> getName();
  }
}

$my_client = new Customer;
$my_client -> lastname = 'Doe';
$my_client -> setName('John');

echo '<br>';
echo $my_client -> name . ' (test)<br>';
echo $my_client -> lastname;
?>

The result of the code:
Name: Doe
John (test)
Doe

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Entelis, 2014-08-05
@zooks

Instead of echo, it is better to do var_dump or at least print_r on the entire object, they will clarify a lot for you.
In this case, when you do $this -> name = $name;, a new name property is created on the object.

object(Customer)[1]
  public 'name1' => null
  public 'lastname' => string 'Doe' (length=3)
  public 'name' => string 'John' (length=4)

PS Well, in general, you have some kind of confusion in the code.
If you already write a getName getter, then it should return something, and not make echo a completely different lastname variable.
PPS I want to believe that this example was invented by you for the test, and you do not write getters / setters where there is no need for this

E
Evgeny Komarov, 2014-08-05
@maNULL

Read about "magic methods" . Special attention to __get() and __set().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question