How to instantiate an object according to a Front End event?

Asked

Viewed 83 times

0

Good afternoon, Folks.

I don’t know if my question makes much sense, but here goes.

For example, I have a class that has several functions, and I have my Index.php

Here we go, when I load the index and need to execute a method of a class, how do I instantiate the object of this class and execute the function according to a user action? For example, when the user clicks a button he will instantiate the Object and execute a certain function.

Ex:

Class:

<?php
 class usuario{

 private nome;

 public function getNome(){
  return $this->Nome;
 }
}
?>

Index:

...

$usuario = new usuario();
$usuario->getNome();

...

2 answers

1


If I understand correctly, you want to pass a stock value to know what to do next. Normally you pass parameters by $_GET in the url, $_POST via form or breaking the url when using friendly url.

Passing an action through a link the logic is as follows:

Link:

<a href="index.php?acao=carregausuario">Carregar usuário</a>

Php code:

if(isset($_GET["acao"]))
{
    if($_GET["acao"]=="carregausuario")
    {
        $usuario = new usuario();
        $nome = $usuario->getNome();
    }
}

Then just give one echo $nome; in the place where you have to display that name.

  • Perfect, so it will only generate the object if the correct POST/GET exists?

  • Yes. In this example the object will only be created if get "action" exists and if the value of get "action" equals "user load".

0

From HTML you cannot run a PHP code. What you can do is use javascript to make an http request for a PHP script that runs what you want.

You can make a call as in the code below in the action you want.

$.ajax({
    type: 'POST', // Ou GET
    url: 'arquivo-com-acao-desejada.php'
});
  • Wouldn’t that make me have to leave the instantiated objects already? What I want to know is how to instantiate the Object according to the user’s action.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.