Jump to content

[SOLVED] New to OOP need a bit of help.


unkwntech

Recommended Posts

The following code snip is giving me an error in PHP5:

<?php
class myClass
{
public $myVar= $self->myFunction(); //Error here
        function myFunction()
         {
                 return 'Hello World';
         }
}
$data = new myClass;
echo $data->myVar;
?>

 

The error is "Unexpected T_VARIABLE".

What am I doing wrong, and is there anything else I should be aware of?

Link to comment
https://forums.phpfreaks.com/topic/134846-solved-new-to-oop-need-a-bit-of-help/
Share on other sites

You can't assign a value to a class variable using methods or funstions.

YOu have to move this to __construct() method

 

<?php
class myClass
{



public $myVar //Error here

        public function __construct()
        {
        $this->myVar = $this->myFunction();
        }

        function myFunction()
         {
                 return 'Hello World';
         }
}
$data = new myClass;
echo $data->myVar;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.