Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Lucas Medeiros

Ajuda classe do livro PHP 5 - WALACE SOARES

Recommended Posts

Eu sou iniciante em PHP e to aprendendo OO pelo livro PHP 5 do Walace Soares, no capitulo 22 ensina a fazer uma classe de manipulação de HTML, eu fiz mas tá dando o seguinte erro:

Notice: Undefined offset: 1 in C:\xampp\htdocs\aprenderphp\class_HTML.inc on line 106

Notice: Undefined offset: 4 in C:\xampp\htdocs\aprenderphp\class_HTML.inc on line 106

Notice: Undefined offset: 0 in C:\xampp\htdocs\aprenderphp\class_HTML.inc on line 138

Notice: Undefined offset: 0 in C:\xampp\htdocs\aprenderphp\class_HTML.inc on line 149

Notice: Undefined offset: 1 in C:\xampp\htdocs\aprenderphp\class_HTML.inc on line 138
ERRO na Estrutura ... Falta fechar a Tag TITLE(id #2)

ja revisei a classe varias vezes, e não estou conseguindo identificar qual o motivo desse erro, imagino q seja algum problema com o array do método AddText, mas não sei oq fazer.

 

Estou usando esse código pra executar a classe

"<?php

include_once './class_HTML.inc';


$html = new HTML();
$id[0] = $html->AddTag("HTML");
$html->AddTag("TITLE",NULL,TRUE,"PHP5- Editora Érica");
$id[1]=$html->AddTag("BODY");
$html->AddTag("P",NULL,TRUE,"Hoje é ".date("d-m-Y"));
$html->EndTag($id[1]);
$html->EndTag($id[0]);



echo $html->toHTML();

?>"

e esta é a classe:

<?php

class HTML {
    /* atributos privados */

    private $html;
    private $att;
    private $text;
    private $tipostag;
    private $idTipo;
    private $tagId;
    private $flgend;

    /* Construtor do método */

    function __construct($tipo = 0, $att = Array(), $end = FALSE) {
        $this->html = Array();
        $this->att = array();
        $this->flgend = array();
        $this->tagId = -1;
        $this->idTipo = 0;
        /* Marcadores (tags) HTML predefinidos */
        $this->addTipoTag("HTML");
        $this->addTipoTag("HEAD");
        $this->addTipoTag("TITLE");
        $this->addTipoTag("BODY");
        $this->addTipoTag("TABLE");
        $this->addTipoTag("TR");
        $this->addTipoTag("TD");
        $this->addTipoTag("A");
        $this->addTipoTag("BR", FALSE);
        $this->addTipoTag("FORM");
        $this->addTipoTag("INPUT", FALSE);
        $this->addTipoTag("SELECT");
        $this->addTipoTag("OPTION");
        $this->addTipoTag("TEXTAREA");
        $this->addTipoTag("IMG", FALSE);
        $this->addTipoTag("DIV");
        $this->addTipoTag("SPAN");
        $this->addTipoTag("BUTTON");
        $this->addTipoTag("SCRIPT");
        $this->addTipoTag("P");

        if ($tipo != 0) {
            $this->AddTag($tipo, $att, $end);
        }
    }

    /* métodos privados */

    /* métodos protegidos */

    /* Métodos publicos */

    public function AddTipoTag($desc_tipo, $flgEnd = TRUE) {
        $this->idTipo++;
        $this->tipostag[$this->idTipo] = $desc_tipo;
        $this->tipostag[$desc_tipo] = $desc_tipo;
        $this->flgend[$this->idTipo] = $flgEnd;
        $this->flgend[$desc_tipo] = $flgEnd;

        return $this->idTipo;
    }

    public function AddTag($tipo, $att = array(), $end = FALSE, $text = "") {
        $this->StartTag($tipo, $att, $end);
        if ($text != "") {
            $this->AddText($this->tagId, $text);
        }
        if ($end) {
            $this->EndTag($this->tagId);
        }

        return $this->tagId;
    }

    public function StartTag($tipo, $att = Array()) {
        $this->tagId++;
        $this->html[$this->tagId][0] = FALSE;

        if ($this->flgend[$tipo] === FALSE) {
            $this->html[$this->tagId][0] = TRUE;
        }
        $this->html[$this->tagId][1] = $this->tipostag[$tipo];
        $this->html[$this->tagId][2] = 0; //start
        $this->AddAtt($this->tagId, $att);
        return $this->tagId;
    }

    public function AddAtt($id, $att = Array()) {
        if (!is_array($att)) {
            return FALSE;
        } elseif ($this->html[$id][0] === NULL OR $this->html[$id][1] == NULL) {
            return FALSE;
        }else {
            foreach ($att as $key=>$vlr){
                $this->att[$id][$key]=$vlr;
            }
        }
    }

    public function AddText($id, $text = "", $clear = FALSE) {
        if ($clear) {
            $this->text[$id] = "";
        }
        $this->text[$id].=$text;
    }

    public function EndTag($id) {
        if ($this->html[$id][0] === TRUE) {
            return FALSE;
        } elseif ($this->html[$id][1] != NULL) {
            $this->html[$id][0] = TRUE;
            $this->StartTag($this->html[$id][1]);
            $this->html[$this->tagId[0]] = TRUE;
            $this->html[$this->tagId[2]] = 1;
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function toHTML() {
        if ($this->tagId == -1) { // abre if1
            return FALSE;
        } //fecha if1
        else {//abre else 1
            $htmltext = "";
            foreach ($this->html as $key => $value) {//abre foreach1
                if ($value[0] == FALSE) {//abre if1 de dentro do foreach1
                    $htmltext = "<p> ERRO na Estrutura ... Falta fechar a Tag " .
                            $this->tipostag[$value[1]] . "(id #" . $key . ") </p>";
                    return $htmltext;
                }//fecha if1 de dentro do foreach
                if ($value[2] == 0) {//abre if2 dentro do foreach1
                    //start
                    $htmltext.="<" . $value[1];
                    if (is_array($this->att[$key])) {//abre if 3
                        foreach ($this->att[$key] as $att => $value) {//abre foreach2
                            if ($att == "_") {//abre
                                $htmltext.=" " . $value;
                            } //fecha
                            else {//abre
                                $htmltext.=" " . $att . "=\"" . $value . "\"";
                            }//fecha
                        }//fecha foreach 2
                    }//fecha if 3
                    $htmltext.=">";
                    if ($this->text[$key] != "") {//abre if 4
                        $htmltext.=$this->text[$key];
                    }//fecha if 4
                }//fecha if 2
                if ($value[2] == 1) {//abre if 5
                    //End
                    if ($this->flgend[$value[1]] === TRUE) {//abre if 6
                        $htmltext.="</" . $value[1] . ">";
                    }
                    if ($value != "IMG")
                        $htmltext.="\n";
                }//fecha if 6
            }//fecha if5
            return $htmltext;
        }//fecha else1
        return False;
    }

//fecha método toHTML
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Meio loucura aprender Orientação a Objetos em cima de HTM, ainda mais com essa classe que você deu o exemplo.

Sei não....

 

Da uma lida no Wiki primeiro sobre oq é:

https://pt.wikipedia.org/wiki/Orienta%C3%A7%C3%A3o_a_objetos

 

Uma olhadinha no php.net tmb é bem vindo:

http://php.net/language.oop5

 

Tem um artigo do devmedia q sempre indico tmb:

http://www.devmedia.com.br/introducao-a-orientacao-a-objetos-em-php/26762

Compartilhar este post


Link para o post
Compartilhar em outros sites

Obrigado, já tinha dado uma pesquisada por fora e sabia q esse erro era por causa do index do array, mas não consigo identificar o por que de dar esse erro.

O código dessa classe faz parte de um dos capítulos do livro q estou usado pra aprender, e preciso dele pra seguir adiante com o livro, já revisei diversas vezes o código, linha por linha, mas ele simplesmente não funciona. Retornando esse erro.

 

as linhas aos quais o erro se refere

106- método addText

 

138- if (is_array($this->att[$key])) {//abre if 3
foreach ($this->att[$key] as $att => $value) {//abre foreach2
if ($att == "_") {/
$htmltext.=" " . $value;
}
else {
$htmltext.=" " . $att . "=\"" . $value . "\"";
}
}. do método toHTML
e a 149 -
if ($this->text[$key] != "") {
$htmltext.=$this->text[$key]; do toHTML também
estou a 3 dias tentando resolver isso kkkk, já estou quase desistindo mas vim aqui como uma ultima tentativa, pra ver se consigo seguir em frente com o livro.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Você está usando chaves de array sem testar se elas existem.

É só usar isset() ou array_key_exists. Veja de novo o link que te mandei. Está tudo explicado lá

 

E outra: primeiro aprenda PHP. Depois estude Orientação a Objetos. Não adianta tentar estudar algo usando uma ferramenta que você mal conhece. Vá devagar. Uma coisa por vez. Não adianta estudar o basicão do PHP e depois já ir correndo pra OOP e frameworks. Só vai atrapalhar seus estudos ;)

Compartilhar este post


Link para o post
Compartilhar em outros sites

Valeu, é q to tendo q fazer um projeto pra faculdade e tem de ser orientado a objeto, e acaba ficando mt corrido, inclusive para eu aprender. vou dar uma olhada melhor no que vc mandou e uma estuda melhor no PHP depois tento resolver essa classe. :)

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.