How to display object's property

Hi everyone,
I try to understand “objects” in PHP but fail to do so. At the following example I try to get “ab” on the display
using object’s property and method but all i get is “a”. Here is the code"


<?php
$obj=new class1;
echo "a".$obj->myVar;
class class1
{
public $myVar;
function aaa()
{
    $myVar="b";
}
}
?>

Can anyone explain me why i dont see that “b” and what i should do to see it?
Thanks a lot

You should have called the aaa method before. That method will set the value of myVar. Until then $myVar is empty.

If you had named your “aaa()” function “__construct()” it would have worked, but like praetor points out as it stands you have do :


$obj=new class1; 
$obj->aaa();
echo "a".$obj->myVar; 

Thanks a lot both of you guys. Tou were very helpful. Now i start yo understand all that “Objects” system.

I strogly recommmend that you start learning Object Oriented Progamming (OOP) using c# or java. php while supports objects, has a history of a more of procedural thinking. Declaring a class is not what OOP is about and lots of php tutorials either don’t use OOP at all or use classes in a procedural way. You can write good OOP in php but you need to find good php tutorials. As a fun fact, I’ve learned a great of OOP from java articles, although I’ve written VERY LITTLE java code in my life. But once again is not the language but the concepts and the mindset what’s important.

As far as I can see, the property is never set in any of the examples. :confused:


<?php
class Object
{
    public
        $value;
        
    public function __construct($value){
        $this->value = $value;
    }
}


$obj = new Object('b');
echo 'a' . $obj->value; //ab

Hi Today,
My background is T-SQL and i want to learn PHP in order to manipulate databases on Internet sites. I thought PHP is the best language for data manipulating+Interner programming.

Hi Anthony
Thanks a lot. Bottom line for me, it may sound unprofessional to you, I omitted the two keywords: “this” and “__construct”.
I could survive without __construct had i inserted:"$obj->aaa(); at the beginning of my code after the instanciation.
Thanks a lot.

That sounds like a good plan, you’ll find plenty of help here.

I’m so happy with the assistence i get here !
Thank you so much !

As far as I can see, the property is never set in any of the examples

Lol, how did I miss that? Clearly I need to be more careful at details and remember that ‘this’ is not optional in php :))