Jump to content

Recommended Posts

Hello everyone,

 

I was experimenting a bit with php today and i was trying to find out if it is possible to create an object, give it an object attribute and access this objects attributes. I try this in the operation display().

$this->var1->var2 generates an error (var1 is an object of class b). The constructing of var 1 goes well since it echoes what i wrote in the construct function. But $this->var1->var2 does not work. What am i doing wrong in this experiment?

 

Thanks for your help :)

 

Bram

 

------------CODE--------------

 

<html>

<head>

</head>

<body>

<?php

 

class a

{

public $var1;

public function display()

{

$this->var1 = new b(10); //var1 is object

echo "trying to access attribute \$var2 of object \$var1 $this->var1->var2";

}

}

 

class b

{

public $var2;

public function __construct($c)

{

$this->var2=$c;

echo "inside class b \$var2 has value $this->var2";

}

}

 

 

$test = new a();

$test->display();

?>

</body>

</html>

Class b needs to extend class a.

 

Also you should really put the class definitions in a separate file and include it.

 

Thanks for the tip, I know about putting the class definitions in another file. I didn't know i needed to extend in this case too. I changed 'class b' into 'class b extends a'. It still gives the same error message though

 

Catchable fatal error: Object of class b could not be converted to string in /var/www/test/test.php on line 13

 

line 13 corresponds to

 

echo "trying to access attribute \$var2 of object \$var1 $this->var1->var2";

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.