Skip to content

Instantly share code, notes, and snippets.

@lucenarenato
Created July 15, 2019 18:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucenarenato/af47e4f9ecda50681c67f854c1de079b to your computer and use it in GitHub Desktop.
Save lucenarenato/af47e4f9ecda50681c67f854c1de079b to your computer and use it in GitHub Desktop.
Rumo a ZCE

Rumo a ZCE

[Rumo a ZCE] Re: Pergunta do dia: 3005 B

Em quinta-feira, 13 de dezembro de 2018 07:51:41 UTC-3, Danielson Xavier escreveu: Se essa pergunta é repetida aqui no grupo, peço desculpas e é só apagar depois. Só lembro de algumas opções da resposta

Qual a saída do código seguinte?

getMessage() . PHP_EOL; } finally { echo $e->getMessage(); } A) NULL B) Error Error C) Error Notice: Undefined variable: e D) Nada é impresso //**********************************************************************************************************************************************************************// O include não quer incluir à pasta raiz, já tentei vários códigos e nada.

Me ajudem por favor, inclusive já até tentei configurar a pasta pera achando que o erro era lá, mas não era, ou corrigi errado. Realmente no $path é aquele caminho ? estranho ter um $path com .'\curl_php\', talvez retirando 1 barra funcione. Tem isso aqui que encontrei no stackoverflow, talvez lhe ajude ou dê um norte. Link: https://stackoverflow.com/questions/7378814/are-php-include-paths-relative-to-the-file-or-the-calling-code

t's relative to the main script, in this case A.php. Remember that include() just inserts code into the currently running script.

That is, does it matter which file the include is called from

No.

If you want to make it matter, and do an include relative to B.php, use the FILE constant (or DIR since PHP 5.2 IIRC) which will always point to the literal current file that the line of code is located in.

include(dirname(FILE)."/C.PHP");

Are PHP include paths relative to the file or the calling code? I'm having trouble understanding the ruleset regarding PHP relative include paths. If I run file A.PHP- and file A.PHP includes file B.PHP which includes file C.PHP, should the relative path to C.PHP be in relation to the location of B.PHP, or to the location of A.PHP? That is, does it matter which file the include is called from, or only what the current working directory is- and what determines the current working directory? 16

If include path doesn't start with ./ or ../, e.g.:

include 'C.php'; // precedence: include_path (which include '.' at first), // then path of current .php file (i.e. B.php), then .. If include path starts with ./ or ../, e.g.:

include './C.php'; // relative to '.'

include '../C.php'; // also relative to '.' The . or .. above is relative to getcwd(), which defaults to the path of the entry .php file (i.e. A.php).

Tested on PHP 5.4.3 (Build Date : May 8 2012 00:47:34).

(Also note that chdir() can change the output of getcwd().) dir -> a.php -> c.php

  • dir2 -> b.php To include a in b you need to include("../a.php");

To include b in c you need to include("dir2/b.php");

//**********************************************************************************************************************************************************************// Vinicius, é o seguinte... realmente é bem estranho, mas ao colocar um número float na chave de um array, ela é transformada em int, logo todas as linhas do tipo: $a[0.17] = 0.17 $a[0.34] = 0.34 ... Se tornam na verdade: $a[0] = 0.17 $a[0] = 0.34 ... Quando finalmente o $i sai do inteiro 0 para 1, chega na condição de parada ($i < 1.02) e não executa o $a[1.02] = 1.02 (que seria $a[1] = 1.02. Logo, no final do código, $a só tem 1 valor, o último valor associado antes de $i chegar à 1.02 que seria 0.85. Espero ter ajudado. Eu errei essa de verdade.

Em segunda-feira, 11 de fevereiro de 2019 22:11:22 UTC-2, viniciu...@kafnet.com.br escreveu: Ola, nao entendi o porque do resultado ser 1

Em quinta-feira, 13 de dezembro de 2018 14:21:08 UTC-2, Danielson Xavier escreveu: What the code outputs?

1, 3=>2, 5=>3] + [4,5,6]; echo implode(', ', array_keys($a)); A) Fatal error B) 1, 3, 5, 6, 7, 8 C) 1, 3, 5, 0, 2 D) 0, 1, 2, 3, 4, 5 Bruno Castro 09:04 (Há 1 hora) para Rumo C) 1, 3, 5, 0, 2 não entendi pq deu 0,2, pode explicar? Adiel Cristo 09:16 (Há 57 minutos) para rumo-a-certificacao-php Olá Bruno, No segundo array criado, [4, 5, 6], quando você não informa os índices eles são criados a partir de 0, resultando em [0 => 4, 1 => 5, 2 => 6]. Após isso, na união de arrays (+), quando há indíces iguais, os elementos do array da esquerda são mantidos, e os do array da direita são ignorados [1]. [1] http://php.net/manual/pt_BR/language.operators.array.php //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Se possível alguém explicar esta segunda questão do tópico... A reposta é 3, porém não entendi. Quando faz $o = new a; vai chamar o __construct que vai elevar a variável $val para 2. Em seguida a variável é chamada por função ($o()) que vai chamar __invoke elevando $val para 3. Entendi no momento que escrevo que a função __toString não é chamada pelo echo. Deixando $val como 3. Sérgio qua, 30 de jan 14:54 (Há 19 horas) para Rumo A variável $val quando é passada para o função __invoke é um interger e logo não é chamado a função __toString. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// What the code outputs? val = 2; } } function test(a $a) { if ($a) { echo $a->val; } } $a = null; test($a); A) NULL B) 2 C) Fatal Error because $a is not an instance of a D) Nothing is printed //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Qual a saída do script? getMessage() . PHP_EOL; } finally { echo $e->getMessage(); } A) NULL B) Error Error C) Error Notice: Undefined variable: e D) Nada é impresso //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Category: Functions. Which elements does the array returned by the function pathinfo() contain? A: root, dir, file B: dirname, filename, file extension C: dirname, basename, extension D: path, file letra C //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Category: Object-Oriented PHP. Sample code: var = "1"; throw $e;} catch (theExceptionTwo $e) {$this->var = "2"; throw $e;} } catch (theExceptionOne $e) {$this->var = "3"; } catch (theExceptionTwo $e) {$this->var = "4"; } } } try { $test = new theClass; } catch (theExceptionTwo $e) {$this->var = "5"; } catch (theExceptionOne $e) {$this->var = "6"; } catch (theExceptionZero $e) {$this->var = "7"; } echo $test->var; ?>

What is the output of the sample code above?

A: 2 B: 3 C: 4 D: 5 E: 7

Obs.: pergunta de ontem, domingo (dia 28/06). Me corrijam se eu estiver errado. Na parte de cima temos várias classes de Exception estendendo da anterior exceto a theException. Quando há a criação do objecto na linha $test = new theClass; o construtor entra em ação e lança a theExceptionTwo. Logo o código deve ir testar o primeiro catch daquele bloco try, que seria a linha catch (theExceptionOne $e) {$this->var = "3"; }. Como theExceptionTwo estende de theExceptionOne, pode-se dizer que theExceptionTwo é um ExceptionOne também, então o código entra neste bloco catch que associa o $var com a string "3".

Letra B //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Category: Security.

Which combination of the following filtering techniques prevents cross-site scripting (XSS) vulnerabilities?

A: None of the above. B: Enable magic_quotes_gpc . C: Strip all occurrences of the string javascript. D: Strip all occurrences of the string $lt; script.

letra A

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Category: Databases.

When a query that is supposed to affect rows is executed as part of a transaction, and reports no affected rows, it could mean that: [ Choose 2 ]

A: The transaction failed B: The transaction affected no lines C: The transaction was rolled back D: The transaction was committed without error Segundo o manual em http://php.net/manual/en/mysqli.affected-rows.php diz o seguinte: An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error. Diz que o resultado zero acontece em três casos: Nenhum registro foi atualizado Nenhum registro foi casado na cláusula WHERE A query ainda não foi executada Porém as respostas não fazem alusão à estes itens... Talvez por eliminação seja a letra A) e B), pois a B sabe-se que é verdade (primeiro item), C) não é verdade porque se a consulta mudar vários registros, o retorno da consulta será o número de linhas afetadas, não importando se vai fazer commit ou rollback. E a letra D) não é verdade pois, novamente, realizando commit ou rollback não importa para o quantitativo de linhas afetadas.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Category: PHP Basic.

What is the difference between the spaceship operator (<=>) and the strcmp() function?

A: There is no difference in functionality B: strcmp() returns a Boolean value, the spaceship operator a number C: strcmp() does a case-intensive comparison, the spaceship operator does not D: The spaceship operator returns -1, 0 or 1; strcmp() may return any integer

[ retornando, após DOIS anos de hibernação ] Letra D). Todas as duas funções, tanto o spaceship operator como o strcmp() realizam comparações case sensitive. Mas o strcmp() retorna um número inteiro de acordo com a distância de diferença do primeiro caractere encontrado diferente. Exemplo: http://sandbox.onlinephpfunctions.com/code/dd3ffde0ed6c86ccf61504941352d20a2c622924

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// What is the output of the following code?

G 1 =>o 2=>o 3=>d 4=> 5=>l 6=>u 7=>c 8=>k 9 =>! Ou seja, não existe a posição 10, o que fará com que o substr returne vazio Executando o código pelo sand php notei o seguinte. Quando $start = 10, realmente retorna string(0) "", porém a partir de $start = 11, a função retorna bool(false). Observei no manual da função substr teve uma modificação na versão 7 dizendo o seguinte: If string is equal to start characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case. Questão bem específica. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Qual a saída do código seguinte? getMessage() . PHP_EOL; } finally { echo $e->getMessage(); } A) NULL B) Error Error C) Error Notice: Undefined variable: e D) Nada é impresso R:B //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// What the code will output? val = 2; } } function test(a $a) { if ($a) { echo $a->val; } } $a = null; test($a); A) NULL B) 2 C) Fatal Error because $a is not an instance of a D) Nothing is printed Alternativa c //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// What the code outputs?

Thiago Silva thiago.silva.tsa@gmail.com seg, 11 de fev 23:21 para rumo-a-certificacao-php

A função count(), conta o número de elementos de uma variável (Que neste caso ficou $a[1.02] ). o For atribuiu o valor de 1.02 para o i quando atingiu a condição. Então $a[$i] = $i, ficou assim $a[1.02] = 1.02; Somente um valor dentro do array.

Vinicius, é o seguinte... realmente é bem estranho, mas ao colocar um número float na chave de um array, ela é transformada em int, logo todas as linhas do tipo: $a[0.17] = 0.17 $a[0.34] = 0.34 ... Se tornam na verdade: $a[0] = 0.17 $a[0] = 0.34 ... Quando finalmente o $i sai do inteiro 0 para 1, chega na condição de parada ($i < 1.02) e não executa o $a[1.02] = 1.02 (que seria $a[1] = 1.02. Logo, no final do código, $a só tem 1 valor, o último valor associado antes de $i chegar à 1.02 que seria 0.85. Espero ter ajudado. Eu errei essa de verdade.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Os 10 tópicos das questões são (em escala de importância):

  • Alta Base do PHP Programação Orientada à Objetos Segurança
  • Média Funções Recursos Web Arrays Strings
  • Baixa Formato de dados e tipos Entrada / Saída Banco de Dados

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

List of Exam Topics

PHP Basics Functions Data Format & Types Syntax Operators Variables Control Structures Language Constructs and Functions Namespaces Extensions Config Performance/bytecode caching Arguments Variables References Returns Variable Scope Anonymous Functions, closures Type Declarations XML Basics SimpleXML XML Extension Webservices Basics SOAP JSON DateTime DOMDocument Web Features Object Oriented Programming Security Sessions Forms GET and POST data Cookies HTTP Headers HTTP Authentication HTTP Status Codes

I/O Files Reading Writing File System Functions Streams Contexts Instantiation Modifiers/Inheritance Interfaces Return Types Autoload Reflection Type Hinting Class Constants Late Static Binding Magic (_*) Methods Instance Methods & Properties SPL Traits Configuration Session Security Cross-Site Scripting Cross-Site Request Forgeries SQL Injection Remote Code Injection Email Injection Filter Input Escape Output Encryption, Hashing algorithms File uploads PHP Configuration Password hashing API Strings & Patterns Databases & SQL Arrays Quoting Matching Extracting Searching Replacing Formatting PCRE NOWDOC Encodings SQL Joins Prepared Statements Transactions PDO Associative Arrays Array Iteration Array Functions SPL, Objects as arrays Casting Error Handling Handling Exceptions Errors Throwables ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Fique atento as seguintes dicas:

Agende seu exame logo após a compra do voucher! Se você deixar pra última hora corre o risco de não conseguir encontrar uma data e/ou horário. Atenção ao selecionar o exame! No meu caso, selecionei o exame 200-550 (ZCPE) que é relacionado ao PHP 5.5, porém, existe o exame 200-710 (ZCE) que é relacionado ao PHP 7.1. Fique atento. Não esqueça de levar 2 documentos com foto, pois é solicitado no momento de realização do exame.

A prova consiste em 70 questões geradas aleatoriamente Questões variam com níveis de dificuldade Baseada em PHP 5.5 Algumas abordam mais de um tópico ao mesmo tempo Questões cobrem 10 tópicos principais do PHP Você tem 90 minutos para completar a prova

Depois de 24 a 48 horas você aparecerá nas “páginas amarelas” da Zend e entre 1 e 2 meses receberá pelo correio o Certificado impresso através do correio (quando o meu chegar posto a imagem).

Outras Dicas

Dicas: Domine o simulado do taylorlopes (http://taylorlopes.com/como-obter-sua-certificacao-php-zend/), se você já está praticamente acertando 90% dele vc já está preparado, mas tente acertar 100% (pq não?) O erro é seu maior aliado, alguns simulados não terão a explicação e somente a resposta forçando você a ter que correr atrás da explicação e isso vai te ajudar. Creio que não caiu nada realmente exclusivo da versão 7.1, de novo mesmo caiu strict_types 2x, variadics 2x que nem é tão novo. É bom estar por dentro de closures, orientação a objetos, funções no geral, late static binding, pdo, o mínimo de entendimento de xml e arrays se teve umas 4 questões foi muito.. Não demore pra marcar/fazer a prova. Minha estratégia de estudo foi basicamente ler cada livro de cada vez com calma e fazendo os exercícios depois de ter terminado, foquei nos simulados e exercícios nos últimos meses.

Simulados

Testar código PHP online

http://sandbox.onlinephpfunctions.com/

Testar expressões regulares online (REGEX)

http://www.phpliveregex.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment