Magento2 – Call Functions from Block in Controller

blockscontrollersmagento2

Say I want to call a function from a Block while inside my Controller class which outputs on screen, how would i go about this?

Code for New/Module/Controller/Hello/World.php :

  <?php
  namespace New/Module/Controller/Hello/;
  class World extends \Magento\Framework\App\Action\Action 
  {

 public function execute()
 {
    echo '<p>"Hello World"</p>';
    var_dump(__METHOD__);

    divide(10,1);  <-- trying to do this 
 }
 }

Code for New/Module/Block/Calculator.php

<?php 
namespace New\Module\Block; 
class Calculator{ 
public function divide($number1, $number2) 
{ 
return $number1/$number2; 
}
public function multiply($number1,$number2){
return $number1*$number2; 
} 
public function add($number1,$number2){ 
return $number1+$number2;
}  
public function sub($number1,$number2){
return $number1-$number2;  
} 
} 

I'm attempting to create a calculator and I'm not even sure this is the best way to go about calling functions to output on screen.

Any help would be much appreciated 🙂

Best Answer

You can call block methods by creating instance of that class.

<?php
      namespace New/Module/Controller/Hello/;
      class World extends \Magento\Framework\App\Action\Action 
      {


        /**
         * Calculator
         *
         * @var \New\Module\Block\Calculator
         */
        public $calculator;

        public function __construct(
        \Magento\Framework\App\Action\Context $context, 
        \New\Module\Block\Calculator $calculator
        ) {
            $this->calculator = $calculator;
            return parent::__construct($context);
        }

     public function execute()
     {
        echo '<p>"Hello World"</p>';
        var_dump(__METHOD__);

        //divides(10,1);  <-- trying to do this 

        $this->calculator->divide(10,1);
     }
     }
Related Topic