learning-php Posted September 20, 2013 Share Posted September 20, 2013 Can somebody could help me please , I am php beginner student. Property Panic (2) Good job, now we have some properties.But right now $teacher and $student are the same, which should be changed immediately, correct? :-) The solution: we have to create a constructor to create different objects. This constructor is also a method, but you don't need to worry about this fact just yet. The syntax: public function __construct($prop1, $prop2) {$this->prop1 = $prop1;$this->prop2 = $prop2;} So you should remember the public keyword and the arrow notation. Some new things: You're creating a function bound to a class (a method).The constructor method has to be called __construct().Finally, the weird way to assign the values: $this->prop1 = $prop1 means that the value you pass in the __construct() function via the new keyword is assigned to $this, which represents the object you are dealing with, and ->prop1 is the actual property of the object. By creating a new instance using the new keyword, you actually call this __construct() method, which constructs the object. And that's why we have to pass in some arguments when we create an instance of a class, since this is how the properties get set!Instructions The public properties $firstname, $lastname and $age should get a value via a constructor.Change the code, so $teacher's:$firstname is "boring",$lastname is "12345",$age is 12345Add your $firstname, $lastname and $age to $student.echo the $age of $student. <?php class Person { public $isAlive = true; public $firstname; public $lastname; public $age; function __construct($firstname,$lastname,$age) { $this->firstname = $firstname; $this->lastname = $lastname; $this->age =$age; } } $object1 = new person("Tired","54321",54321); $object2 = new person("Your","name",99); echo '$isAlive->isalive', echo '$firstname->age', ?> I get this message Oops, try again! Is there still a '$teacher' variable? Quote Link to comment https://forums.phpfreaks.com/topic/282323-property-panic-2-whats-wrong-help/ Share on other sites More sharing options...
TOA Posted September 20, 2013 Share Posted September 20, 2013 (edited) $teacher is referring to (my best guess) $object1. And you need to start your echo with the object your calling - ie: $object2->age, not $firstname->age $teacher = new person('Boring','12345','12345'); $student = new person('Me','Myself',99); echo $student->age; Edited September 20, 2013 by TOA Quote Link to comment https://forums.phpfreaks.com/topic/282323-property-panic-2-whats-wrong-help/#findComment-1450450 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.