1
class A
{
    public function child1()
    {
        $var1 = 'abc';
    }
}

class B extends A
{
    public function child1()
    {
        echo parent::$var1; // Return error undefined class constant 'var1'
    }
}

How can i access $var1 in this situation ? Expected result: 'abc'

1
  • 2
    You can't, that variable is local to the function, you'd have to make it a class property. Here's the manual for object basics. Commented Jun 23, 2019 at 4:58

2 Answers 2

1

First you cannot do class B extends class A. The correct syntax would be class B extends A:

class A
{
    public function child1()
    {
        $var1 = 'abc';
        return $var1;
    }
}

class B extends A
{
    public function child1()
    {
        echo parent::child1(); 
    }
}

$temp = new B;
$temp->child1();

Now what I've done is return the $var1 in your class A.

You cannot call echo parent::$var1; because it is inside a function, so you call the parent function echo parent::child1();.

working example here

Sign up to request clarification or add additional context in comments.

Comments

1

You need to make $var1 a class property. See following code:

<?php
    class A
    {
        protected $var1;
        public function child1()
        {
            $this->var1 = 'abc';
        }
    }

    class B extends A
    {
        public function child1()
        {
            parent::child1();
            echo $this->var1;
        }
    }
$b = new B();
$b->child1();    
?>

Comments

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.