Hi,
I have created a class “friendClass” and tried to echo it. It prints nothing without any errors, not sure what was it going on? Any helps would be appreciated!
class friendClass{
//attributes - variable
public $name;
public $sex;
public $title;
public $country;
//methods - function
public function eat(){}
public function watch(){}
public function drive(){}
public function speak(){}
}
$friend1 = new friendClass;
$friend2 = new friendClass;
$friend3 = new friendClass;
$friend4 = new friendClass;
$friend1 -> name = "Bach";
$friend1 -> title = "Muscian";
$friend1 -> sex = "Male";
$friend1 -> country = "Germany";
$friend1 -> eat("Bread");
$friend1 -> speak("German");
$friend1 -> drive("Horse");
$friend1 -> watch("Beethoven");
echo "Name is: ".$friend1->name;
<?php
class friendClass {
//attributes - variable
public $name;
public $sex;
public $title;
public $country;
//methods - function
public function eat() {
}
public function watch() {
}
public function drive() {
}
public function speak() {
}
}
$friend1 = new friendClass;
$friend1->name = "Bach";
echo "Name is: " . $friend1->name;
?>
your problem comes that the last command you gave php was to make $friend4 the object for the friend class so if you switch $friend1 with $friends4 should work perfectly. objects have a 1 & 1 relationship so lets say you have 1 and 2 and a class FOO. So if we make 1 an the object of the FOO class 1 = new FOO;. 1 and FOO have a 1 & 1 relationship only 1 can use the FOO class. Now if we make 2 the object of the FOO class 2 = new FOO; 1 loses it’s relationship to FOO because your last command to php was make 2 the 1 & 1 relationship. sorry for the crummy explanation but i hope you understand the why
If I understand you correctly, the red bit is not correct because you can make as many instances (copies) of a class as you like and each instance will have its own copy of the class stored in memory.
For example:
Say you have a class called myCar.
then it is correct to do the following:
car1 = new myCar();
car2 = new myCar();
Both car1 and car2 will have their own copies of the myCar class in memory. You can change the properties of say car1 without affecting the same property in car2.