As per your actual requirement, in first phtml file add below code :
$arr=array(23,4);
echo $this->getLayout()->createBlock("Vendor\Modulename\Block\Display")->setData('var1', $arr)->setTemplate("Vendor_Modulename::test2.phtml")->toHtml();
In second phtml i.e. test2.phtml add
$catIds=$block->getData("var1");
$arr=array();
foreach($catIds as $catId){
$_productCollection=$block->setCustomValue($catId);
foreach ($_productCollection as $_product){
$currentId=$_product->getId();
if (!in_array($currentId, $arr)){
echo $_product->getData("name");echo "<br/>";
}
$arr[]=$_product->getId();
}
}
In app/code/Vendor/Modulename/Block/Display.php add below code:
protected $_productCollectionFactory;
protected $_categoryFactory;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
$productCollectionFactory,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Framework\View\Element\Template\Context $context
) {
$this->_categoryFactory = $categoryFactory;
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context);
}
public function setCustomValue($value)
{
$categoryId = $value;
$category = $this->_categoryFactory->create()->load($categoryId);
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;
}