magento2 – How to access a variable declared in a phtml from another phtml?


You can configure the variable with register from the first phtml, then you get the value in the second phtml with registry

To do things right without directly injecting the objectManager into phtml, you must create some function in your product block, therefore:

In your block: app/code/Vendor/Modulename/Block/Custom.php

assuming its variable name is: $tech

_coreRegistry = $coreRegistry;
    }

    /**
     * Set var data
     */
    public function setTechData($data)
    {
        $this->_coreRegistry->register('tech', $data);
    }

    /**
     * Get var data
     */
    public function getTechData()
    {
        return $this->_coreRegistry->registry('tech');
    }
}

Then in your first phtml:


setTechData($tech); ?>

In the second phtml:

getTechData(); ?> //you'll get your tech value here

You can do it in phtml to proof Without the block solution:

First phtml:

create("MagentoFrameworkRegistry")->register('tech', $tech);
?>

Second phtml:

create("MagentoFrameworkRegistry")->registry('tech');
echo $techData;
?>