Blog Home PHP

spl_autoload_register com classe Autoloader

			  
Este exemplo chama uma classe Autoloader.

Arquivo Autoloader.php
< ? php

 //Simple autoloader, so we don't need Composer just for this.

class Autoloader
{
    public static function register()
    {
        spl_autoload_register(function ($class) {
            $file = str_replace('\\', DIRECTORY_SEPARATOR, $class).'class.php';
            if (file_exists($file)) {
                require $file;
                return true;
            }
            return false;
        });
    }
}
? >

Aproveitando as classes Gato, Cao e Animal:

																		 
																		 
Arquivo autoload5.php

< ? php	
include "Autoloader.php"

Autoloader::register();

$garfield	= new Gato();
$pateta		= new Cao();
$mobdick	= new Animal();

echo $garfield->diz()	. '
'; echo $pateta->diz() . '
'; echo $mobdick->respira(). '
'; ? >

Teste agora →

spl_autoload_register com exception 3

			  
Este exemplo lançará uma exceção e demonstrará o bloco try/catch.

< ? php
spl_autoload_register(function ($name) {
    echo "Quero carregar $name.\n";
    throw new Exception("Incapaz de carregar $name.");
});

try {
    $obj = new NonLoadableClass();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
? >

				

Teste agora →

spl_autoload_register 2

			  
Este exemplo tenta carregar uma interface ITest
			  
< ? php

spl_autoload_register(function ($name) {
    var_dump($name);
});

class Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
? >

				

Teste agora →

spl_autoload_register 1

			  
Este exemplo tenta carregar as classes MyClass1 e MyClass2
			  
< ? php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj  = new MyClass1();
$obj2 = new MyClass2();
? >

				

Teste agora →

usando namespaces

			  
< ? php namespace Felino;
  class Gato { 
    static function diz() {echo 'miau';}  } ? >
	
< ? php namespace Canino;
  class Cao {
    static function diz() {echo 'auau';}  } ? >

< ? php namespace Vida;
  class Animal {
    static function respira() {echo 'ar';}  } ? >

< ? php namespace animais;
  include 'arquivo1.php';
  include 'arquivo2.php';
  include 'arquivo3.php';
  use Felino as feline;
  use Canino as canine;
  use Vida as animate;
  echo feline\Gato::diz(), "
\ n"; echo canine\Cao::diz(), "
\ n"; echo animate\Animal::respira(), "
\ n"; ? >

Teste agora →

mysqli_fetch_fields

$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
	printf("Connect failed: %s\n", mysqli_connect_error());
	exit();
}

$query = "SELECT * from user ORDER BY ID LIMIT 5";

if ($result = mysqli_query($link, $query)) {

	/* Get field information for all columns */
	$finfo = mysqli_fetch_fields($result);

	foreach ($finfo as $val) {
		printf("Name:     %s\n", $val->name);
		printf("Table:    %s\n", $val->table);
		printf("max. Len: %d\n", $val->max_length);
		printf("Flags:    %d\n", $val->flags);
		printf("Type:     %d\n\n", $val->type);
	}    
	mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);			
				

Teste agora →

mysqli_stmt_bind_param INSERT sem ID

$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = mysqli_prepare($link, "INSERT INTO user (firstname, lastname, email, pass) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "ssss", $firstname, $lastname, $email, $pass);

//$id = 4;
$firstname = 'Luis';
$lastname = 'Medeiros';
$email = "joelma.medeiros@bitpixel.com.br";
$pass = "123456";

/* execute prepared statement */
mysqli_stmt_execute($stmt);

$rows = mysqli_stmt_affected_rows($stmt);

/* fetch values */
/*
while (mysqli_stmt_fetch($stmt)) {
	printf ("%s %s\n", $first, $last);
}
*/
printf("Linhas afetadas pelo INSERT %s\n", $rows);

/* close statement and connection */
mysqli_stmt_close($stmt);

/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM user WHERE firstname='Luis' AND lastname='Medeiros'");
printf("%d Linha apagada.\n", mysqli_affected_rows($link));

/* close connection */
mysqli_close($link);			

Teste agora →

mysqli_stmt_bind_param INSERT

$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = mysqli_prepare($link, "INSERT INTO user VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "issss", $id, $firstname, $lastname, $email, $pass);

$id = 4;
$firstname = 'Luis';
$lastname = 'Medeiros';
$email = "joelma.medeiros@bitpixel.com.br";
$pass = "123456";

/* execute prepared statement */
mysqli_stmt_execute($stmt);

//$rows = mysqli_stmt_affected_rows($stmt);

/* fetch values */
/*
while (mysqli_stmt_fetch($stmt)) {
	printf ("%s %s\n", $first, $last);
}
*/
//printf ("Linhas afetadas %s\n", $rows);

/* close statement and connection */
mysqli_stmt_close($stmt);

/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM user WHERE ID=4");
printf("%d Row deleted.\n", mysqli_affected_rows($link));

/* close connection */
mysqli_close($link);

Teste agora →

mysqli_stmt_bind_param SELECT

$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = mysqli_prepare($link, "SELECT firstname, lastname FROM user WHERE firstname=?");
mysqli_stmt_bind_param($stmt, "s", $firstname);

$firstname = "Dime";

/* execute prepared statement */
mysqli_stmt_execute($stmt);

/* bind result variables */
mysqli_stmt_bind_result($stmt, $first, $last);

$rows = mysqli_stmt_affected_rows($stmt);

/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
	printf ("%s %s\n", $first, $last);
}

/* close statement and connection */
mysqli_stmt_close($stmt);

/* close connection */
mysqli_close($link);

Teste agora →

mysqli_stmt_bind_param

$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
mysqli_stmt_execute($stmt);

printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));

/* close statement and connection */
mysqli_stmt_close($stmt);

/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", mysqli_affected_rows($link));

/* close connection */
mysqli_close($link);

Teste agora →

mysqli_stmt_fetch PHP

$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT firstname, lastname FROM user ORDER by ID DESC LIMIT 0,5";

if ($stmt = mysqli_prepare($link, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);
	
    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $first, $last);
	
    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf ("%s (%s)\n", $first, $last);
    }
	
    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
				

Teste agora →

mysqli_prepare PHP

				
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$firstname = "Davi";

/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT firstname, lastname FROM user WHERE firstname=?")) {
	
    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $firstname);
	
    /* execute query */
    mysqli_stmt_execute($stmt);
	
    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $firstname, $lastname);
	
    /* fetch value */
    mysqli_stmt_fetch($stmt);
	
    printf("%s is the firstname of %s\n", $firstname, $lastname);
	
    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);

				

Teste agora →
Busca
Destaques
Conheça as novidades da nova versão Bootstrap 4.1.3 lançada em abril de 2018