1

I'm a bit rusty with php, I want to know how I can call the function login available in class2, inside class1. This is the example:

<?php

    require_once("property2.php");

class Class1 
{
      public function __construct()
      {
         $cls2 = new Class2()
      }

      public function method1()
      {
          $cls2->login() //cl2 is undefined 
      }

} ..

//this is the function

...
class Class2
{
     public function __construct()
     {

     }

     //This is the  function to call

     public function login()
     {
       //Some stuff
     }
} ...

Now PHPSTORM say that the variable cls2 is undefined. What I did wrong?

3
  • Should be $this->cls2 Commented Jan 29, 2016 at 16:33
  • 1
    What does Class1 extend??? Commented Jan 29, 2016 at 16:34
  • @u_mulder I tried in method1 as $this->cls2->login() but I get this error in the network tab: Undefined property: Class1::$cls2 in ... the line that I shown before Commented Jan 29, 2016 at 16:37

2 Answers 2

3

When you are setting your variable youre not setting it as a class property. Define a private variable inside your class, and "set it and get it" using the $this keyword.

class Class1 {
    private $cls2;

    public function __construct() {
        $this->cls2 = new Class2();
    }

    public function method1() {
        $this->cls2->login();
    }
}

Another way to achieve this is to use Inheritance, where one class is considered a "parent" class. You would achieve this by using extends

class Class1 {
    public function __construct() {
        //Some stuff
    }

    public function login() {
        //Some stuff
    }
}


class Class2 extends Class1 {
    public function __construct() {
        parent::__construct();
    }

    public function method1() {
        $this->login();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2
class Class1 
{
      public function __construct()
      {
         $cls2 = new Class2();
      }

      public function method1()
      {
          $cls2->login() //cl2 is undefined 
      }

}

When you create Class1 and call $cls2 = new Class2();, $cls2 exists only locally. You have to make it a class property:

class Class1 
{

    public $cls2;

    public function __construct()
    {
       $this->cls2 = new Class2();
    }

    public function method1()
    {
        $this->cls2->login();
    }

}

And then you'll be able to access it using $this keyword.

Also please watch for semicolons.

1 Comment

Oh okay, I understood now. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.