Classes within Classes

Hi all,

 

I have a class thus:

[code]

class Webpage
{
public $system_licence = false;

   public function __construct() {
$system_licence = new Licence;
$system_licence->is_valid = true;
}
}

class Licence {
    public $id = false;
public $start_datetime = false;
public $end_datetime = false;
public $days_remaining = false;
public $is_valid = false;
}

[/code]

In my main page I create an instance of the Webpage class thus:

[code]

$this_page = new Webpage;

if($this_page->system_licence->is_valid == true) {

      // do something

}  

[/code]

However PHP says that is_valid is being dynamically created, even though it is a property of the Licence object which is created within the Webpage object.

Why does it do this please?

0
5 comments

In the Webpage constructor, you create a local variable that goes nowhere instead of assigning a value to the field.

Here's what the code is supposed to look like:

class Webpage
{
   public $system_licence = false;

   public function __construct() {
        $this->system_licence = new Licence;
        $this->system_licence->is_valid = true;
   }
}
0

Sorry - my mistake. I do include the $this-> elements in the constructor but whilst trying to represent it here for you I missed it out.

So, my code does read as you suggest, but the problem still occurs.

0

@Chris

You would need to show the real / test code that shows the issue (that we can copy-paste and see the issue locally), otherwise it's "guess where I have made a mistake / how my real code looks like" ... as your current example shows no such issues:

0

Index.php is at: https://pastebin.com/Tr3D9aLX

Webpage.php is at: https://pastebin.com/sT8BsJpK

You already have the total content of Licence.php i.e.:

<?php
class Licence
{
public $id = false;
public $start_datetime = false;
public $end_datetime = false;
public $days_remaining = false;
public $is_valid = false;
}

You will note that in Webpage.php the $system_licence variable is defined at line 32, created at line 146, and the is_valid value is set at line 153 or 154.

The error concerned is at line 29 of Index where is queries the is_valid as being wrong:

https://1drv.ms/u/s!AoOAUeu7fqnZh_Ni9_sEXT-8mKvh8g

Thanks in advance.

 

0

@Chris

Thanks for the files.

The reason is simple: due to the way how you declared $system_licence and assignment happens in another method (not in constructor) IDE treats system_license as boolean variable (due to public $system_licence = false;) ... which obviously cannot have own fields.

Solution is very simple: use better declaration.

  • Either move "$this->system_licence = new Licence;" line into constructor (constructors have special treatment for field assignments .. and IDE will treat this field as bool OR Licence)
  • or use PHPDoc comment to tell IDE what type that variable is, like this:
/** @var Licence */
public $system_licence;

 

0

Please sign in to leave a comment.