php - MPRandomText 类的对象无法转换为字符串

标签 php string class object

Possible Duplicate:
Object could not be converted to string?

我需要为我的图像创建随机标题,但出现错误

MPRandomText 类的对象无法转换为字符串 C:\Program Files (x86)\EasyPHP-5.3.9\www\dir.php 第 42 行

如何将随机文本包含到我的 html 图像标题中?

    class MPRandomText
    {
    var $filepath;
    var $sepstring;
    var $fixchar;
    var $textfix;
    var $contents;
    var $random;
    var $errors;
    // initiate object and start functions
    function MPRandomText($filepath, $sepstring, $textfix)
        {
        $this->filepath = $filepath;
        $this->textfix = $textfix;
        $this->sepstring = $sepstring;
        $this->errors = "";
        $this->contents = "";
        $this->FileToString();
        }
    // read file contents into string variable
    function FileToString()
        {
        if (!$this->filepath || !file_exists($this->filepath))
            $this->errors = "Could not find text file at ".$this->filepath;
            else {
            @$filePointer = fopen($this->filepath, "r");
            if (!$filePointer) $this->errors = "Text file could not be opened.";
            if ($this->errors == "")
                {
                $this->contents = fread($filePointer, filesize($this->filepath));
                fclose($filePointer);
                if (!$this->textfix) $this->HTMLContent();
                $this->MakeArray();
                }
            }
        }
    // if importing an HTML page, drop everything outside of (and including) the <body> tags
    function HTMLContent()
        {
        $test = stristr($this->contents, "<body");
        if ($test !== false)
            {
            $test = stristr($test, ">");
            if ($test !== false)
                {
                $test = str_replace("</BODY>", "</body>", $test);
                $test = explode("</body>", substr($test, 1));
                if (count($test) > 1) $this->contents = $test[0];
                }
            }
        }
    // convert the file text into a list using separation character
    function MakeArray()
        {
        $array = explode($this->sepstring, $this->contents);
        if (count($array) > 0)
            {
            $this->contents = $array;
            $this->CleanTextList();
            } else $this->errors = "Text file contents are empty or could not be read.";
        }
    // clean up the list of empty values and extra white space
    function CleanTextList()
        {
        $result = array();
        if (is_array($this->contents))
            {
            for ($n=0; $n<count($this->contents); $n++)
                {
                $string = trim($this->contents[$n]);
                $test = trim($string."test");
                if (!empty($string) AND $test != "test") $result[] = $string;
                }
            if (count($result) > 0)
                {
                $this->contents = $result;
                $this->RandomString();
                }
            }
        }
    // get random text string from list
    function RandomString()
        {
        reset($this->contents);
        srand((double) microtime() * 1000000);
        shuffle($this->contents);
        $this->random = $this->contents[0];
        }
    // send finished results to be printed into HTML page
    function GetResults()
        {
        if ($this->errors != "") return $this->errors;
            else
            {
            if ($this->textfix == true) $this->random = htmlentities($this->random);
            return $this->random;
            }
        }
    }

//-------------------------------------------------------------------------------------------------
//  FUNCTION AND VARIABLE TO CREATE RANDOM TEXT INSTANCE
//-------------------------------------------------------------------------------------------------

// create variable to store instance references
$MPRandomTextHandles = array();

// function to create new handle and import random text
function MPPrintRandomText($MPTextFile = "random.txt", $MPSepString = "*divider*", $MPTextToHTML = false)
    {
    global $MPRandomTextHandles;
    for ($n=0; $n<250; $n++)
        {
        if (!isset($MPRandomTextHandles[$n]))
            {
            $MPRandomTextHandles[$n] = new MPRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
            break;
            }
        }
    print($MPRandomTextHandles[$n]->GetResults());
    return $MPRandomTextHandles[$n];
    }


    /* Начало конфигурации */
$thumb_directory = 'img/thumbs';
$orig_directory = 'img/imag';
/* Конец конфигурации */
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$title1='גילוף פסלים בעץ';
$i=0;


/* Открываем папку с миниатюрами и пролистываем каждую из них */
$dir_handle = @opendir($thumb_directory) or die("There is an error with your 
image directory!");
$i=1;

while ($file = readdir($dir_handle))
{
/* Пропускаем системные файлы: */
if($file=='.' || $file == '..') continue;
$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));

/* Используем название файла (без расширения) в качестве названия изображения: */
// $title = implode('.',$file_parts);
// $title = htmlspecialchars($title);
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
$title = MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);

/* Если расширение разрешено: */
if(in_array($ext,$allowed_types))
{

/* Выдаем каждое фото: */
echo '<li>
        <a href="'.$orig_directory.'/'.$file.'" rel="lightbox[pasel]">
            <img title="'.$title.'" src="'.$thumb_directory.'/'.$file.'" width="72" height="72" alt="גילוף פסלים בעץ" />
        </a>
    </li>';
}
}
/* Закрываем папку */
closedir($dir_handle);

最佳答案

$title 是 MPRandomText 的实例。您在输出中连接了 $title,但 MPRandomText 没有实现 __toString(),因此它无法转换为字符串。

<?php 
$title = MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
// MPPrintRandomText returns an instance of MPRandomText

/* Если расширение разрешено: */
if(in_array($ext,$allowed_types))
{

/* Выдаем каждое фото: */
echo '<li>
    <a href="'.$orig_directory.'/'.$file.'" rel="lightbox[pasel]">
        <img title="'.$title.'" src="'.$thumb_directory.'/'.$file.'" width="72"     height="72" alt="גילוף פסלים בעץ" />
    </a>
</li>';
// concatenating $title here will fail because MPRandomText does not implement __toString()
}
}
?>

关于php - MPRandomText 类的对象无法转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10349236/

相关文章:

php - 无法将 JSON 数据正确加载到 Spinner 中

r - R中的操作重载

c++ - C++中类字段对齐与对象实例对齐的关系?

c++ - 如何在 C++ 中从 "public ref class"创建一个公共(public)变量?

php - 上传 14000 行 csv 文件时出错

在 firefox 上使用 Mysql 的 PHP 报告

javascript - Cloudinary如何在php中生成签名

Java:从特定字符后开始的字符串中获取子字符串

c - C语言中的 "wide character string"是什么?

python - 方法会更改两个实例,即使仅应用于其中一个实例