Ir para conteúdo

POWERED BY:

Arquivado

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

visitante_php

problema com funcao variavel....

Recommended Posts

eu to criando uma classe e nela coloquei uma funcao variavel q nao esta dando certo

 

 

ta assim

 

protected function Resize()
	{
		if ($this->w && ($this->width < $this->height)) {
				$this->w2 = ($this->h / $this->height) * $this->width;
			} else {
				$this->h2 = ($this->w/ $this->width ) * $this->height;
			}
			$this->imagem_p = imagecreatetruecolor($this->w, $this->h);
			$this->imagem = $this->methodCreateFrom($this->files['tpm_name']);
			imagecopyresampled($this->imagem_p, $this->imagem, 0, 0, 0, 0, $this->w2, $this->h2, $this->width, $this->height);
			/** upa a imagem redimensionada */
			$this->imagetype($this->imagem_p, $this->dir."/".$this->rename, 100);
	}

 

e a variavel vem de

 

 

 

protected function getImageInfo(){
		list($this->width,$this->heigth) = getimagesize($this->files['tpm_name']);
		$type = explode('/',$this->tipo);
		if($type['0'] == 'image')
		{
			switch($type['1'])
			{
				case 'jpeg':
				$this->image = 'jpeg';
				$this->methodCreateFrom = 'imagecreatefromjpeg';
				$this->imagetype = 'imagejpeg';
				break;
				case 'gif': 
				$this->image = 'gif';
				$this->methodCreateFrom = 'imagecreatefromgif';
				$this->imagetype = 'imagegif';
				break;
				case 'png': $image = 'png';
				$this->methodCreateFrom = 'imagecreatefrompng';
				$this->imagetype = 'imagepng';
				break;
			}
			return $this->image;
			return $this->imagetype;
			return $this->methodCreateFrom;	
		}
		return $this->width;
		return $this->heigth;
	}

 

esta gerando os seguintes erros...:

Warning: Division by zero in E:\xampp\xampplite\htdocs\ajax\upload.class.php on line 221

 

Fatal error: Call to undefined method Upload::methodCreateFrom() in E:\xampp\xampplite\htdocs\ajax\upload.class.php on line 224

ja conferi esta td certinho.....o q faço? =/

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bom dia,

 

Vou dar meus pitacos sobre os problemas.

 

Sobre o warning:

 

Vendo a sua função, você retorna o seguinte no segundo script:

 

return $this->heiGTh;

 

Entretanto, pede uma divisão por heiGHt!

 

$this->w2 = ($this->h / $this->height)

 

é uma "typo" minima, mas que está fazendo seu código dividir por zero, creio eu.

 

 

Sobre o fatal:

 

Talvez seja derivado do primeiro erro?

 

Bom, espero que eu não tenha falado besteira ;)

 

Boa sorte!

Compartilhar este post


Link para o post
Compartilhar em outros sites

qual eh a linha 221 e qual a linha 224 ?

 

outra coisa, na linha que tem

list($this->width,$this->heigth) = getimagesize($this->files['tpm_name']);

nao seria

 

list($this->width,$this->heigth) = getimagesize($this->files['tmp_name']);
?

 

flw xD/

Compartilhar este post


Link para o post
Compartilhar em outros sites

Existe algum motivo para fazer mais de um return ?

O construtor "return" interrompe e sai da função. Independentemente do que esteja posteriormente.

Se o que pretende é enviar mais de um valor, retorne-os como um array.

 

return $this->image;
			return $this->imagetype;
			return $this->methodCreateFrom;	
		}
		return $this->width;
		return $this->heigth;

 

para chamar uma função variável usando métodos de um objeto, adicione o prefixo $

 

original:

$this->methodCreateFrom;

 

sugestão:

$this->$methodCreateFrom;

 

fonte

 

function return

http://jp2.php.net/manual/pt_BR/functions....ning-values.php

 

return

http://php.net/return

 

funções variáveis

http://php.net/manual/pt_BR/functions.variable-functions.php

Compartilhar este post


Link para o post
Compartilhar em outros sites

a unica mudança q fiz foi a q você sugeriu....e apareceu as mesmas mensagens....

 

 

protected function getImageInfo( ){
		list( $this->width,$this->heigth ) = getimagesize( $this->files['tpm_name'] );
		$type = explode( '/' , $this->tipo );
		if( $type['0'] == 'image' )
		{
			switch( $type['1'] )
			{
				case 'jpeg':
				$this->image = 'jpeg';
				$this->$methodCreateFrom = "imagecreatefromjpeg";
				$this->imagetype = 'imagejpeg';
				break;
				
				case 'gif': 
				$this->image = 'gif';
				$this->$methodCreateFrom = "imagecreatefromgif";
				$this->imagetype = 'imagegif';
				break;
				
				case 'png': 
				$this->image = 'png';
				$this->$methodCreateFrom = "imagecreatefrompng";
				$this->imagetype = 'imagepng';
				break;
			}
			return array( $this->image , $this->imagetype , $this->$methodCreateFrom );	
		}
		return array( $this->width , $this->heigth );

 

protected function Resize( )
	{
		if ( $this->w && ( $this->width < $this->heigth ) )
		 {
			$this->w2 = ( $this->h / $this->heigth ) * $this->width;
			}
			else
			{
				$this->h2 = ( $this->w / $this->width ) * $this->heigth;
			}
			$this->imagem_p = imagecreatetruecolor( $this->w , $this->h );
			$this->imagem = $this->$methodCreateFrom( $this->files['tpm_name'] );
			imagecopyresampled( $this->imagem_p, $this->imagem, 0, 0, 0, 0, $this->w2, $this->h2, $this->width, $this->heigth );
			$this->$imagetype( $this->imagem_p, $this->dir."/".$this->rename, 100 );
	}

estou testando assim

 

 

<?php

/**
 * @author 
 * @copyright 2008
 */
include('upload.class.php');
$subir = new Upload('arquivo');
$subir->Rename(3);
$subir->setExtAllowed(array('jpeg','gif','bmp','jpg'));
$subir->setResize(true);
$subir->setTamanho(300,300);
$subir->setPeso(46546354567);
$subir->setDir('teste');
$subir->Execute();

?><form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
  <label>
	<input type="file" name="arquivo" id="arquivo" />
  </label>
  <label>
	<input type="submit" name="button" id="button" value="Submit" />
  </label>
</form>

Compartilhar este post


Link para o post
Compartilhar em outros sites

eu simplifiquei os metodos, mas ainda da problema, os mesmos...

 

protected function Resize( )
	{
		if ( $this->dimension['w'] && ( $this->imageinfo['w'] < $this->imageinfo['h'] ) )
		 {
			$this->w2 = ( $this->dimension['h'] / $this->imageinfo['h'] ) * $this->imageinfo['w'];
			}
			else
			{
				$this->h2 = ( $this->dimension['w'] / $this->imageinfo['w'] ) * $this->imageinfo['h'];
			}
			$this->imagem_p = imagecreatetruecolor( $this->dimension['w'] , $this->dimension['h'] );
			
			switch( $this->imageinfo['type'] )
			{
				case 'GIF':
					$this->imagem = imagecreatefromgif( $this->files['tpm_name'] );
					break;
				case 'JPG':
					$this->imagem = imagecreatefromjpeg( $this->files['tpm_name'] );
					break;
				case 'PNG':
					$this->imagem = imagecreatefrompng( $this->files['tpm_name'] );
					break;
			}
			
			
			
			imagecopyresampled( $this->imagem_p, $this->imagem, 0, 0, 0, 0, $this->w2, $this->h2, $this->dimension['w'], $this->dimension['h'] );
			
			imagejpeg( $this->imagem_p, $this->dir."/".$this->rename, 100 );
			
	}

 

e

 

 

 

protected function getImageInfo( ){
		$type = explode( '/' , $this->files['type']);
		if( $type['0'] == 'image' )
		{
			list( $this->imageinfo['w'] , $this->imageinfo['h'] , $this->imageinfo['type'] ) = getimagesize( $this->files['tpm_name'] );
		}
		return $this->imageinfo;
	
	}

 

eu at poderia colocar a classe toda....mas na ultima vez levei sapatada....entao, fico receoso....

 

 

 

public function Execute( )
	{
		if( $this->files['name'] )
		{
			if( $this->resize )
			{
				$this->getExtAllowed( );
				if( $this->peso )
				{
					 if( $this->allowed )
					 {
					 	$this->getNewDimensions( );
					 	$this->getImageInfo( );
					 	$this->Resize( );
					 }
					 else 
					 {
						  echo 'Extensao de arquivo nao permitida!';
					 }
				
				}
				else
				{
					 echo 'Arquivo com peso acima do permitido!';
				}
			}
			else 
			{
			$this->getExtAllowed( );
			if( $this->peso )
			{
				if( $this->allowed )
				{
					move_uploaded_file( $this->files['tmp_name'] , $this->dir.'/'.$this->rename );
				}
				else 
				{
					echo 'Extensao de arquivo nao permitida!';
				}
				
			}
			else
			{
				echo 'Arquivo com peso acima do permitido!';
			}
		}
	}
	
	}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Não por causa dos erros,mas é legal você estudar OO e um pouco de lógica e refazer seu código.

Voltando ao que interessa...

Segundo erro:

$this->imagem = $this->methodCreateFrom($this->files['tpm_name']);

Para:

$this->imagem = eval($this->methodCreateFrom.'('.$this->files['tmp_name'].');');

O primeiro erro é porque o PHP não aceita divisões por 0 (numero/0),e por esse motivo joga esse erro.

 

Ps:não vi o código refeito.

Ps²: não mesclei os posts devido ao intervalo de tempo entre a postagem dos mesmos.

Compartilhar este post


Link para o post
Compartilhar em outros sites

protected function getImageInfo( ){
		list( $this->width,$this->heigth ) = getimagesize( $this->files['tpm_name'] );
		$type = explode( '/' , $this->tipo );
		if( $type['0'] == 'image' )
		{
			switch( $type['1'] )
			{
				case 'jpeg':
				$this->image = 'jpeg';
				$this->$methodCreateFrom = "imagecreatefromjpeg";
				$this->imagetype = 'imagejpeg';
				break;
				
				case 'gif': 
				$this->image = 'gif';
				$this->$methodCreateFrom = "imagecreatefromgif";
				$this->imagetype = 'imagegif';
				break;
				
				case 'png': 
				$this->image = 'png';
				$this->$methodCreateFrom = "imagecreatefrompng";
				$this->imagetype = 'imagepng';
				break;
			}
			return array( $this->image , $this->imagetype , $this->$methodCreateFrom );	
		}
		return array( $this->width , $this->heigth );

você não fez como orientei..

 

é no momento da conistrução da chamada da função e não no momento da atribuição da variável

 

errado:

$this->$methodCreateFrom = "imagecreatefromjpeg";

manter como estava:

$this->methodCreateFrom = "imagecreatefromjpeg"; // aqui é feito a atribuição do valor à propriedade

 

para invocar a função sim, deve colocar o sinal $

 

$this->$methodCreateFrom(aqui dentro os padrâmetros necessários da função que está chamando);

 

 

 

Example 2 (página do manual) http://php.net/manual/pt_BR/functions.variable-functions.php

<?php
class Foo
{
	function MetodoVariavel()
	{
		$name = 'Bar';
		$this->$name(); // Isto chama o método Bar()
	}

	function Bar()
	{
		echo "Bar foi chamada!";
	}
}

$foo = new Foo();
$funcname = "MetodoVariavel";
$foo->$funcname();  // Isto chama $foo->MetodoVariavel()

?>

 

obs: você já alterou varias coisas no script antes de eu ter postado isso

apenas preste atenção onde precisa corrigir no script atual ou volte onde estava.. ( você salva backups não é ? )

 

nota: evite dar muitas voltas pra fazer coisas simples

Primeiramente, faça funcionar, depois, com o tempo você melhorará suas técnicas e poderá aplicar formas mais simples e eficientes na construção dos códigos.

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.